1. Revenue per customer is higher than the ledger

Debug the AIEasyFan-out trap

joins · row duplication · aggregation

Open in Colab
How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

A teammate asked an AI assistant for a "revenue per customer" report and shipped what it wrote. The job runs without errors and the output looks reasonable. Finance has now compared it to the ledger: the report's total revenue is too high, and only some customers are off.

The AI-written code is in the answer cell. Find the bug and fix it.

Input tables

orders

One row per order.

Column Type Description
order_id BIGINT Unique per order.
customer_id BIGINT The customer who placed the order.
order_date DATE Date the order was placed.
order_amount DECIMAL(10,2) Full value of the order in rupees.

payments

One row per payment attempt. An order can have no rows here, one row, or several: a failed attempt followed by a retry, an order paid in two or three parts, or occasionally an order the gateway charged twice in full.

Column Type Description
payment_id BIGINT Unique per payment attempt.
order_id BIGINT The order the attempt was for. A few rows point to orders that are not in orders.
paid_at TIMESTAMP_NTZ When the attempt happened.
amount DECIMAL(10,2) Amount of this attempt in rupees.
method STRING upi, card, netbanking or wallet.
status STRING SUCCESS, FAILED or PENDING.

Requirement

  • An order is paid if it has at least one SUCCESS payment.
  • A customer's revenue is the sum of order_amount over their paid orders. Each paid order counts once, for its order_amount, however many payments it took and whatever those payments add up to.
  • Every customer in orders must appear in the result. A customer with no paid orders has paid_orders = 0 and revenue = 0.00.

Expected output

One row per customer.

Column Type Description
customer_id BIGINT
paid_orders BIGINT Number of paid orders.
revenue DECIMAL(12,2) Sum of order_amount over paid orders.

The AI-written code

from pyspark.sql import functions as F


def solve(spark):
    """Revenue per customer from paid orders."""
    orders = spark.table("orders")
    payments = spark.table("payments")

    # Only successful payments count towards a paid order
    successful_payments = payments.filter(F.col("status") == "SUCCESS")

    # Left join so that customers without any paid orders are still included
    orders_with_payments = orders.join(successful_payments, on="order_id", how="left")

    # Aggregate per customer
    result = orders_with_payments.groupBy("customer_id").agg(
        F.countDistinct(
            F.when(F.col("payment_id").isNotNull(), F.col("order_id"))
        ).alias("paid_orders"),
        F.coalesce(
            F.sum(F.when(F.col("payment_id").isNotNull(), F.col("order_amount"))),
            F.lit(0),
        )
        .cast("decimal(12,2)")
        .alias("revenue"),
    )

    return result

Explanation

Show explanationGives the answer away. Try the problem first.

The bug

The code joins orders to the successful rows of payments and then sums order_amount:

orders_with_payments = orders.join(successful_payments, on="order_id", how="left")
...
F.sum(F.when(F.col("payment_id").isNotNull(), F.col("order_amount")))

orders has one row per order. payments has one row per payment attempt. After the join, the result has one row per successful payment, and order_amount is repeated on each of those rows. An order paid in two parts contributes its amount twice, an order paid in three parts three times.

In this data, 24 of the 122 paid orders have more than one successful payment: 21 were paid in parts and 3 were charged twice by the gateway. That inflates revenue for 18 of the 39 customers. The report totals 20,22,750.08 against a correct 16,29,561.15.

What makes it hard to spot:

  • paid_orders is correct. The code uses countDistinct, which hides the repeated rows for the count. Whoever wrote it handled the duplication for one column and not for the other.
  • 21 customers are exactly right, because each of their paid orders has a single successful payment. Spot-checking a few customers can easily pass.
  • Nothing fails. The row count is right and every number is plausible.

The approach

Before joining two tables, write down the grain of each one and the grain of the result.

  • orders: one row per order.
  • payments: one row per payment attempt.
  • orders joined to payments: one row per payment attempt (or one row for an order with no match, in a left join).

order_amount is a fact about an order. Summing it is only valid on a set of rows that has one row per order. So bring payments down to one row per order first, then join:

WITH paid_orders AS (
    SELECT DISTINCT order_id
    FROM payments
    WHERE status = 'SUCCESS'
)
SELECT ...
FROM orders o
LEFT JOIN paid_orders p ON o.order_id = p.order_id
GROUP BY o.customer_id

paid_orders has at most one row per order, so the join cannot repeat an order. After that, COUNT(p.order_id) counts the paid orders and a plain SUM is correct.

The general rule: aggregate or de-duplicate the "many" side to the grain of the "one" side before the join, not after it.

Common wrong answers

Adding .distinct() after the join. It removes nothing. The joined rows differ in payment_id, paid_at and amount, so no two rows are identical. Revenue stays wrong.

SUM(DISTINCT order_amount). It appears to work, because the repeated amounts of one order collapse to one. But it also collapses two different orders that happen to have the same amount. Customer 117 has two separate paid orders of 499.00 each, and this version counts only one of them. De-duplicating on a measure is never safe; the key is order_id, not the amount.

Switching to an inner join, or filtering status = 'SUCCESS' after the left join. Both drop every order without a successful payment, and with them customers 129, 134, 139 and 140, who have no paid orders at all. The result has 35 rows instead of 39. The requirement says those customers must appear with 0 and 0.00.

Summing payments.amount instead of order_amount. It looks like a neat way around the duplication, and for orders paid in parts it gives the right number. It answers a different question though: cash collected, not the value of paid orders. Three orders here were charged twice in full by the gateway, and this version counts them at double their value. The second charge is a refund waiting to happen, not revenue.

dropDuplicates(["order_id"]) after the join. This gives the right answer. It is still the weaker fix: it keeps an arbitrary payment row per order and relies on nobody later using a payment column from that DataFrame. Reducing payments before the join makes the grain explicit.

Edge cases in the data

Case Where What it catches
Order paid in two or three SUCCESS payments 21 orders The bug itself.
Order charged twice in full 3 orders, customers 108, 121 and 133 Summing payments.amount.
FAILED attempt, then SUCCESS several orders Forgetting to filter on status before deciding an order is paid.
Orders with only FAILED or PENDING attempts 18 orders Treating "has a payment row" as "paid".
Orders with no payment rows 10 orders Inner join drops them.
Customers with no paid orders 129, 134, 139 and 140 Inner join drops the customer; missing COALESCE gives NULL instead of 0.00.
Two paid orders with the same amount customer 117, 499.00 twice SUM(DISTINCT order_amount).
Payments pointing to orders not in orders 2 rows, order ids 9001 and 9002 Driving the query from payments instead of orders.