AI Coding Interview Practice Beta

Cake Club Billing Bug Squash

Four bug reports against a cake-box subscription's billing code: a wrong charge, billing dates that drift, the wrong default plan and a report that never finishes. Hidden tests run when you say you're done, like in a real round.

Bug squash · Hard · 75-minute time box · Python 3.10+

Start in the browser

Same format as rounds at Stripe and Google

Quick start

  1. Download the starter repo and unzip it.
  2. Open the folder in your editor, with any AI assistant you like.
  3. Run the tests from the repo's folder: python3 -m unittest discover -s tests. The tests for the stages you haven't done yet fail.
  4. Set a timer for 75 minutes and work through the stages in order.

Stages

  1. Bug 1: Annual subscribers are charged 100 times too much
  2. Bug 2: Billing dates drift after a short month
  3. Bug 3: New signups get the wrong default plan
  4. Bug 4: The month-end report never finishes

What it practices

  • reading unfamiliar code
  • finding root causes, not just symptoms
  • date arithmetic
  • making slow code fast without changing its results
  • checking AI-written fixes beyond the visible tests

Where you'd see this

This is a bug squash problem. Bug reports written as symptoms, in code you've never seen. Reproduce each one, find the cause, fix it. There's nothing new to build. The skill is narrowing the search: reproduce the bug, make a guess, test the guess, and only then change code. The fix is often a line or two. Finding it is the work.

Stripe · Bug squash (bug bash) round

No AI unless told Official: Stripe published this

Stripe says you and the interviewer work on a real historical bug from an open-source project. Candidates describe a repo and a bug report: reproduce it, find the root cause, fix it and confirm the fix.

Stripe hasn't published an AI policy for candidates. Assume no AI unless your recruiter says otherwise. Our Stripe guide »

Google · Code comprehension round (pilot)

AI allowed Reported by candidates or the press

Business Insider reported a pilot where you review an existing codebase and find bugs, with interviewers looking at debugging and how you check AI output.

Google confirmed Gemini is the assistant in the pilot. Our guide to AI-assisted interviews »

Practicing for one of these? Stripe's version asks you to reproduce the bug, find the root cause, fix it and confirm the fix. Do all four for each bug here, out loud, before you run the hidden tests.

This is an original Interview Cake problem written in the same format. It isn't a question from any of these companies, and formats change, so check your invite or ask your recruiter what to expect.

The scenario

Cake Club is Crumb & Co.'s cake-box subscription. Its billing service is a small Python package of seven modules (about 320 lines). It loads the plans from the bakery's price sheet, signs people up for monthly or annual plans, runs a daily billing job, shows the Plans page, and gives finance a month-end report.

Four bug reports have come in. Each one has a test file that reproduces it, and there are hidden tests too, like the ones an interviewer runs after you say you're done.

Time box: 75 minutes. Work through the bugs in order. Each one has its own test file and doesn't depend on the others.

  1. Bug 1: annual subscribers are charged 100 times too much. An annual Classic box costs $32,000.00 instead of $320.00. Done when every annual amount is right.
  2. Bug 2: billing dates drift after a short month. Someone who signed up on January 31 is billed on February 28, and then on the 28th forever. Done when subscribers are billed on their own day again after a short month.
  3. Bug 3: new signups get the wrong default plan. Since the Plans page went live, people who don't pick a plan sometimes get the Mini box. Done when the default is the first plan on the menu again.
  4. Bug 4: the month-end report never finishes. At 20,000 invoices and 30,000 payments, finance's report job times out. Done when it's fast and every number in it is exactly what it was before.

The README in the download has the full bug reports and the billing rules. test_existing.py passes from the start; test_stage1.py to test_stage4.py go with bugs 1 to 4. Run them with python3 -m unittest discover -s tests.

How to work this problem with an AI assistant

Read before you prompt. Spend the first few minutes on the README's rules, the code and the tests, with the assistant closed. You can't judge its fixes if you don't know what the code is meant to do.

Make it show its evidence. When the assistant tells you what a value is or what a function does, ask it to point to the lines that show it, and read them yourself.

Green tests are where checking starts. Before you call a bug done, try a case of your own in scratch.py. Then run the hidden tests.

Prompts that work on any bug report:

  • "Before you change anything, tell me what this function is supposed to do according to the README, and show me the lines that do each part."
  • "What calls this, and what does each caller expect from it?"
  • "Give me three inputs that would tell a real fix apart from one that only passes this test."
  • "What did you change, and what else depends on the code you changed?"

Self-check rubric

Here's what interviewers look for in debugging rounds, with or without AI. Be honest about which column you were in. The walkthrough below says what each row looks like for these four bugs.

Area Strong signals Weak signals
Understanding the codebase Builds a picture of the code from the code and the tests. Knows who calls a function, and what the rules are, before changing it. Changes the function named in the bug report without reading its callers. Takes the assistant's account of the code on trust.
Correctness Fixes each root cause, wherever it does damage. Keeps every rule the code is meant to follow. Passes the visible tests and stops. Fixes the case in the report and nothing else.
Tests and verification Tries cases of their own before calling a bug fixed. Runs the hidden tests and can explain any that fail. Iterates on AI patches until the visible tests go green. Is surprised by the hidden tests.
Code quality Small fixes in the right place, with one source of truth for each rule. Copies the same fix into several places. Rewrites working code and changes what it does.
Use of AI Makes the assistant show its evidence and checks its fixes against cases it didn't test. Accepts a fix because the assistant sounded sure. Lets it "simplify" code nobody has read.
Communication For each bug: the symptom, the root cause, what else it affected, and the cases that prove the fix. "Fixed it, the tests pass."

Walkthrough

Show the walkthrough (spoilers)Hide the walkthrough

Bug 1: annual subscribers are charged 100 times too much

Root cause. The comment on Plan says price is "monthly price, in dollars". It isn't. Since version 2.0 every amount in the app is whole cents, and load_price_sheet converts the sheet's dollars on the way in. test_existing.py checks it too: a Classic box is Plan("classic", "Classic box", 3200, 1). Whoever wrote annual plans believed the comment, so _annual_amount converts cents to cents again: to_cents(3200 * 10) is 3,200,000 cents. The same belief is in two more places: the annual invoice line (the receipt) and the Plans page format the cents as if they were dollars, so both show $32,000.00.

# models.py: the comment was the bug's source, so fix it too
price: int  # monthly price, in cents

# billing.py
def _annual_amount(plan: Plan) -> int:
    return plan.price * ANNUAL_MONTHS_CHARGED

def line_description(plan, interval):
    ...
    return f"{plan.name}, annual: {boxes} boxes for {format_cents(_annual_amount(plan))}"

# pages.py
annual = plan_amount(plan, Interval.YEAR)
lines.append(f"{plan.name}: {format_cents(plan.price)} a month, or {format_cents(annual)} a year")

Plausible-but-wrong AI fixes. Dropping to_cents in _annual_amount, or dividing by 100, fixes the charge, which is all the visible tests check. The receipt and the Plans page still say $32,000.00. Fixing the receipt but not the Plans page is another easy miss. "Fixing" the data to match the comment (storing dollars) breaks test_existing.py and every monthly price. Rounding to whole dollars, like plan.price // 100 * 10 * 100, gets $190.00 for a $19.99 plan. The hidden tests check the receipt, the Plans page and a price with cents in it.

Weak prompt: "Annual plans charge $32,000 instead of $320. Fix it."
Strong prompt: "What unit is Plan.price in? Check it against load_price_sheet and the tests, not the comment. Then find everything that computes or shows an annual amount, and make them all use one function."

Bug 2: billing dates drift after a short month

Root cause. next_billing_date takes only the previous billing date, so it can't know the subscriber's real billing day once a short month has cut it down. Jan 31 becomes Feb 28, and from then on the "same day next month" is the 28th. The information it needs is started_on.day. next_annual_date has the same flaw: an annual plan that started on February 29 stays on the 28th even in the next leap year.

# dates.py
def next_billing_date(previous: date, day: int | None = None) -> date:
    day = day or previous.day
    year = previous.year + previous.month // 12
    month = previous.month % 12 + 1
    return date(year, month, min(day, days_in_month(year, month)))

# billing.py: from the day they signed up on
def _following_date(subscriber):
    day = subscriber.started_on.day
    if subscriber.interval is Interval.MONTH:
        return next_billing_date(subscriber.next_bill_on, day)
    return next_annual_date(subscriber.next_bill_on, day)

Plausible-but-wrong AI fixes. The obvious fix is "if the previous date was the last day of its month, bill on the last day of the next month." It passes every visible test, because the reported subscriber signed up on the 31st. It fails the sister in the bug report, who signed up on the 30th: Feb 28 is the last day of February, so she's billed on March 31. It's also wrong for January 29 in a leap year. Fixing monthly plans only leaves the February 29 annual plan on the 28th forever. The hidden tests check all of these.

Weak prompt: "After February, people who signed up on the 31st get billed on the 28th. Fix it."
Strong prompt: "next_billing_date only gets the previous date. What information does it need to get back to someone's billing day after a short month? Fix monthly and annual the same way, and show me the dates for the 29th, 30th and 31st through a leap year."

Bug 3: new signups get the wrong default plan

Root cause. Catalog.plans() returns the catalog's own list, not a copy. pricing_page sorts that list in place, cheapest first, so after anyone views the Plans page the menu's first plan, which is the default, is the Mini box. That's why a restart "fixes" it for a while. The printed menu comes out in price order too. And holiday_menu extends the same list with December's specials, so they join the regular menu, and get added again every time the holiday menu is shown. Both are mutation through a shared reference.

# catalog.py
def plans(self) -> list[Plan]:
    """Every plan, in menu order: a new list each time."""
    return list(self._plans)

# pages.py: no need to change the list anyway
plans = sorted(catalog.plans(), key=lambda plan: plan.price)
...
plans = catalog.plans() + list(specials)

Plausible-but-wrong AI fixes. Changing pricing_page to use sorted() fixes the reported case and leaves the holiday menu adding specials to the catalog. Remembering the default plan when the catalog is created passes the visible tests while the menu itself is still reordered. Hard-coding "classic" as the default breaks as soon as the bakery reorders its price sheet. The hidden tests check the printed menu after the Plans page, the holiday menu shown twice, and a price sheet with a different first plan.

Weak prompt: "The default plan is wrong after the Plans page loads. Fix default_plan."
Strong prompt: "Find every caller of Catalog.plans(). Does any of them change the list? Fix it so no caller can change the menu, whatever it does with the list it gets."

Bug 4: the month-end report never finishes

Root cause. For every invoice, month_end_report loops over every payment: O(invoices × payments). At 20,000 invoices and 30,000 payments that's 600 million comparisons. One pass over the payments into a dictionary keyed by invoice id, then one pass over the invoices, makes it O(invoices + payments). See Big O notation if that's new.

paid = {}
for payment in payments:
    if payment.status is PaymentStatus.FAILED:
        continue
    if payment.paid_on > month_end:
        continue  # it'll be in next month's report
    amount = -payment.amount_cents if payment.kind is PaymentKind.REFUND else payment.amount_cents
    paid[payment.invoice_id] = paid.get(payment.invoice_id, 0) + amount

return [
    ReportRow(invoice.id, invoice.subscriber_id, invoice.total_cents, paid.get(invoice.id, 0))
    for invoice in invoices
    if invoice.issued_on <= month_end
]

Plausible-but-wrong AI fixes. This is the trap Omar warned about: "Please don't change what the report says." Fast rewrites often drop a rule along the way, and the visible test, a month where every invoice gets paid, can't tell. The easy ones to lose:

  • the month-end cut-off for payments, the rule with the "next month's report" comment;
  • rows for unpaid invoices, when the rewrite builds rows from the payments;
  • the invoices' order, when it sorts them, or goes through a set of invoice ids or the payments' dict;
  • a KeyError for a payment against an invoice that isn't in the report.

The hidden tests check each of these. Before you rewrite a function for speed, write down every rule it applies, and check each one in your version.

Weak prompt: "This report is too slow. Optimize it."
Strong prompt: "List every rule month_end_report applies, including the order of the rows. Then make it linear, keep every rule, and give me a small example for each rule that the old and new versions agree on."

Files in the starter repo

Here's everything in the starter repo, so you can look around before you download it. Click a file to open it.

README.md 94 lines
# Cake Club billing: bug squash

Cake Club is Crumb & Co.'s cake-box subscription: pick a box, and a cake turns up every month. This is the
billing side. It loads the plans from the bakery's price sheet, signs people up, bills them on the right
days, shows the Plans page, and gives finance a report at the end of each month. Four bug reports have come
in. Find and fix them.

## Running the tests

Python 3.10 or newer, standard library only (nothing to install). From this folder:

    python3 -m unittest discover -s tests

To run one bug's tests: `python3 -m unittest discover -s tests -p "test_stage1.py"`

- `tests/test_existing.py` covers behaviour that already works. It passes now; keep it passing.
- `tests/test_stage1.py` to `tests/test_stage4.py` go with bugs 1 to 4. Each fails until its bug is fixed.
- There are hidden tests too, like the ones an interviewer runs after you say you're done. In the browser
  workspace, choose "Hidden tests" in the Run menu. Locally, download `hidden-tests.zip` from the problem
  page and unzip it where you unzipped the starter. It adds a `hidden_tests` folder next to `tests`. Then,
  from this folder, run `python3 -m unittest discover -s hidden_tests`.

## Time box and rules

75 minutes. Work through the bugs in order.

Use any editor and any AI assistant you like. In a real AI-allowed interview you'd be expected to explain
and verify everything the AI writes, so practice that too.

Change anything under `cakeclub/`, but don't edit the tests. For each fix, be ready to say what the root
cause was and why your change fixes it.

## How it works

| File | What it does |
|---|---|
| `cakeclub/money.py` | `to_cents`, `format_cents`, `percent_off` |
| `cakeclub/models.py` | `Plan`, `Subscriber`, `Invoice`, `Payment` |
| `cakeclub/catalog.py` | `Catalog`, `load_price_sheet` (which reads `data/price_sheet.csv`), and `menu_export`, the printed menu |
| `cakeclub/dates.py` | `next_billing_date`, `next_annual_date` |
| `cakeclub/billing.py` | `sign_up` and `run_billing`, the daily billing run |
| `cakeclub/pages.py` | `pricing_page` (the Plans page) and `holiday_menu` |
| `cakeclub/reports.py` | `month_end_report` for finance |
| `CHANGELOG.md` | What changed, and when |

The rules, as the business wants them:

- The menu order is the order of the price sheet. The first plan on the menu is the default for people who
  sign up without choosing one. The printed menu and the holiday menu use menu order; the Plans page lists
  plans cheapest first.
- Plans are monthly or annual. An annual plan costs 10 months' price and brings 12 months of boxes.
- Subscribers are billed the day they sign up, then on that same day of the month every month. When a month
  is too short for their day, they're billed on its last day, and on their own day again after that. Annual
  plans work the same way, a year at a time.
- The daily billing run bills everyone whose billing date has come. If a run was missed, it catches up: one
  invoice for each date that went by.
- The month-end report has one row per invoice issued on or before the last day of the month, in the order
  the invoices are given. Each row shows what's been paid against the invoice by the end of the month:
  successful payments minus refunds. Failed payments don't count, and a payment made after the month ends
  goes in next month's report.

## Bug 1: Annual subscribers are charged 100 times too much

> From: customer support
>
> Fay signed up for the annual Classic box this morning and her card was charged $32,000.00. It should be
> $320.00: ten months of $32.00, the pay-for-10-get-12 deal. Her receipt email doesn't add up either. We've
> refunded her and turned off annual signups until this is fixed. Monthly subscribers look fine.

## Bug 2: Billing dates drift after a short month

> From: a subscriber, forwarded by support
>
> I signed up on January 31 because I wanted my cake at the end of each month. I was billed on January 31
> and February 28, which is fair. But then March was billed on the 28th, and April too. My sister signed up
> on January 30 and the same thing happened to her.

## Bug 3: New signups get the wrong default plan

> From: the shop
>
> Since the new Plans page went live, people who sign up without choosing a plan get the Mini box. The
> default has always been the first plan on our menu, the Classic box, and nobody has touched the price
> sheet. It doesn't happen every time: after a restart it's fine for a while. The printed menu at the
> counter came out in a funny order on Tuesday, too.

## Bug 4: The month-end report never finishes

> From: Omar, finance
>
> The month-end report was fine in the summer, but November's ran for 15 minutes and then the job was
> killed. We're up to about 20,000 invoices and 30,000 payments a month. Please don't change what the report
> says, only how long it takes: its numbers go straight into the books, and its rules are the ones we agreed
> with our accountants.
CHANGELOG.md 23 lines
# Changelog

## 2.4 (November 2026)

- The Plans page (`pages.pricing_page`): every plan, cheapest first.
- The holiday menu (`pages.holiday_menu`) for December's specials.

## 2.3 (June 2026)

- The month-end report for finance (`reports.month_end_report`).

## 2.2 (March 2026)

- Annual plans: pay for 10 months, get 12.

## 2.0 (January 2026)

- All money is whole cents (`int`) now: plan prices, invoice lines, payments. No more floats.
  The price sheet the bakery exports is still in dollars, and `load_price_sheet` converts it.

## 1.0 (2025)

- Monthly cake boxes.
cakeclub/__init__.py 1 line
"""Cake Club: monthly and annual cake-box subscriptions for Crumb & Co."""
cakeclub/billing.py 72 lines
"""Signing people up, and the daily billing run."""

from datetime import date

from cakeclub.catalog import Catalog
from cakeclub.dates import next_annual_date, next_billing_date
from cakeclub.models import Interval, Invoice, InvoiceLine, Plan, Subscriber
from cakeclub.money import format_cents, to_cents

# Annual plans: pay for 10 months, get 12.
ANNUAL_MONTHS_CHARGED = 10


def sign_up(catalog: Catalog, subscriber_id: str, email: str, started_on: date,
            plan_code: str | None = None, interval: Interval = Interval.MONTH) -> Subscriber:
    """A new subscriber, on the plan they chose or the catalog's default. They're billed
    for the first time on the day they sign up."""
    plan = catalog.get(plan_code) if plan_code else catalog.default_plan()
    return Subscriber(
        id=subscriber_id,
        email=email.strip().lower(),
        plan_code=plan.code,
        interval=interval,
        started_on=started_on,
        next_bill_on=started_on,
    )


def plan_amount(plan: Plan, interval: Interval) -> int:
    """What one billing period of the plan costs, in cents."""
    if interval is Interval.MONTH:
        return plan.price
    return _annual_amount(plan)


def _annual_amount(plan: Plan) -> int:
    # Plan prices are in dollars, so convert the annual price to cents.
    return to_cents(plan.price * ANNUAL_MONTHS_CHARGED)


def line_description(plan: Plan, interval: Interval) -> str:
    """The invoice line, as the customer's email shows it."""
    if interval is Interval.MONTH:
        return f"{plan.name}, monthly ({format_cents(plan.price)})"
    boxes = plan.boxes_per_month * 12
    return f"{plan.name}, annual: {boxes} boxes for ${plan.price * ANNUAL_MONTHS_CHARGED:,.2f}"


def run_billing(subscribers: list[Subscriber], catalog: Catalog, today: date) -> list[Invoice]:
    """Bills every active subscriber whose next billing date is today or earlier: one invoice
    per date that's come due (someone the run missed twice gets two invoices), dated that
    day. Moves each subscriber's next_bill_on on past today."""
    invoices = []
    for subscriber in subscribers:
        if not subscriber.active:
            continue
        plan = catalog.get(subscriber.plan_code)
        while subscriber.next_bill_on <= today:
            invoices.append(Invoice(
                id=f"INV-{subscriber.id}-{subscriber.next_bill_on:%Y%m%d}",
                subscriber_id=subscriber.id,
                issued_on=subscriber.next_bill_on,
                lines=[InvoiceLine(line_description(plan, subscriber.interval), plan_amount(plan, subscriber.interval))],
            ))
            subscriber.next_bill_on = _following_date(subscriber)
    return invoices


def _following_date(subscriber: Subscriber) -> date:
    if subscriber.interval is Interval.MONTH:
        return next_billing_date(subscriber.next_bill_on)
    return next_annual_date(subscriber.next_bill_on)
cakeclub/catalog.py 57 lines
"""The plans on the menu, and the price sheet they're loaded from."""

import csv
import io

from cakeclub.models import Plan
from cakeclub.money import format_cents, to_cents


class UnknownPlanError(KeyError):
    pass


class Catalog:
    """The plans on the menu, in menu order: the order the bakery lists them in."""

    def __init__(self, plans):
        self._plans = list(plans)
        self._by_code = {plan.code: plan for plan in self._plans}
        if not self._plans:
            raise ValueError("a catalog needs at least one plan")
        if len(self._by_code) != len(self._plans):
            raise ValueError("two plans have the same code")

    def plans(self) -> list[Plan]:
        """Every plan, in menu order."""
        return self._plans

    def get(self, code: str) -> Plan:
        try:
            return self._by_code[code]
        except KeyError:
            raise UnknownPlanError(code) from None

    def default_plan(self) -> Plan:
        """New signups who don't choose a plan get the first plan on the menu."""
        return self._plans[0]


def load_price_sheet(text: str) -> Catalog:
    """Reads the price sheet the bakery exports: a CSV with a header row and the columns
    code, name, monthly_price (in dollars, like 32.00) and boxes_per_month, in menu order."""
    rows = csv.DictReader(io.StringIO(text))
    return Catalog(
        Plan(
            code=row["code"].strip(),
            name=row["name"].strip(),
            price=to_cents(row["monthly_price"].strip()),
            boxes_per_month=int(row["boxes_per_month"]),
        )
        for row in rows
    )


def menu_export(catalog: Catalog) -> str:
    """The printed menu at the shop counter: one line per plan, in menu order."""
    return "\n".join(f"{plan.name} - {format_cents(plan.price)} a month" for plan in catalog.plans())
cakeclub/dates.py 23 lines
"""Billing dates."""

import calendar
from datetime import date


def days_in_month(year: int, month: int) -> int:
    return calendar.monthrange(year, month)[1]


def next_billing_date(previous: date) -> date:
    """The monthly billing date after `previous`: the same day of the next month, or that
    month's last day if it's shorter (Jan 31 -> Feb 28)."""
    year = previous.year + previous.month // 12
    month = previous.month % 12 + 1
    return date(year, month, min(previous.day, days_in_month(year, month)))


def next_annual_date(previous: date) -> date:
    """The yearly billing date after `previous`: the same day a year later, or Feb 28 for
    Feb 29 when next year isn't a leap year."""
    year = previous.year + 1
    return date(year, previous.month, min(previous.day, days_in_month(year, previous.month)))
cakeclub/models.py 71 lines
"""The data the billing service works with."""

from dataclasses import dataclass, field
from datetime import date
from enum import Enum


class Interval(Enum):
    MONTH = "month"
    YEAR = "year"


@dataclass(frozen=True)
class Plan:
    """A cake box you can subscribe to."""

    code: str
    name: str
    price: int  # monthly price, in dollars
    boxes_per_month: int = 1


@dataclass
class Subscriber:
    id: str
    email: str
    plan_code: str
    interval: Interval
    started_on: date
    next_bill_on: date  # moved on by billing.run_billing each time they're billed
    active: bool = True


@dataclass(frozen=True)
class InvoiceLine:
    description: str
    amount_cents: int


@dataclass
class Invoice:
    id: str
    subscriber_id: str
    issued_on: date
    lines: list[InvoiceLine] = field(default_factory=list)

    @property
    def total_cents(self) -> int:
        return sum(line.amount_cents for line in self.lines)


class PaymentKind(Enum):
    PAYMENT = "payment"
    REFUND = "refund"


class PaymentStatus(Enum):
    SUCCEEDED = "succeeded"
    FAILED = "failed"


@dataclass(frozen=True)
class Payment:
    """Money in (a payment) or out (a refund) against one invoice."""

    id: str
    invoice_id: str
    amount_cents: int  # always positive: kind says which way the money went
    paid_on: date
    kind: PaymentKind = PaymentKind.PAYMENT
    status: PaymentStatus = PaymentStatus.SUCCEEDED
cakeclub/money.py 27 lines
"""Money helpers.

to_cents is for amounts that come in from outside, written in dollars: the price
sheet the bakery exports, and the admin form.
"""

from decimal import ROUND_HALF_UP, Decimal


def to_cents(dollars) -> int:
    """'32.00', 32 or Decimal('19.5') dollars -> whole cents, rounding half up."""
    cents = Decimal(str(dollars)) * 100
    return int(cents.quantize(Decimal(1), rounding=ROUND_HALF_UP))


def format_cents(cents: int) -> str:
    """3200 -> '$32.00', 3200000 -> '$32,000.00', -150 -> '-$1.50'."""
    sign = "-" if cents < 0 else ""
    dollars, rest = divmod(abs(cents), 100)
    return f"{sign}${dollars:,}.{rest:02d}"


def percent_off(cents: int, percent: int) -> int:
    """The discount for `percent` (0-100) off, rounded down to a whole cent."""
    if not 0 <= percent <= 100:
        raise ValueError(f"percent must be 0-100, not {percent}")
    return cents * percent // 100
cakeclub/pages.py 24 lines
"""The customer-facing pages: the Plans page and the holiday menu."""

from cakeclub.billing import ANNUAL_MONTHS_CHARGED
from cakeclub.catalog import Catalog
from cakeclub.models import Plan
from cakeclub.money import format_cents


def pricing_page(catalog: Catalog) -> str:
    """The Plans page: every plan, cheapest first, with its monthly and annual price."""
    plans = catalog.plans()
    plans.sort(key=lambda plan: plan.price)
    lines = ["Our plans, cheapest first:"]
    for plan in plans:
        annual = plan.price * ANNUAL_MONTHS_CHARGED
        lines.append(f"{plan.name}: {format_cents(plan.price)} a month, or ${annual:,.2f} a year")
    return "\n".join(lines)


def holiday_menu(catalog: Catalog, specials: list[Plan]) -> str:
    """The December menu: the regular plans in menu order, then the holiday specials."""
    plans = catalog.plans()
    plans.extend(specials)
    return "\n".join(f"{plan.name} - {format_cents(plan.price)} a month" for plan in plans)
cakeclub/reports.py 45 lines
"""Reports for the finance team."""

from dataclasses import dataclass
from datetime import date

from cakeclub.models import Invoice, Payment, PaymentKind, PaymentStatus


@dataclass(frozen=True)
class ReportRow:
    invoice_id: str
    subscriber_id: str
    billed_cents: int
    paid_cents: int

    @property
    def outstanding_cents(self) -> int:
        return self.billed_cents - self.paid_cents


def month_end_report(invoices: list[Invoice], payments: list[Payment], month_end: date) -> list[ReportRow]:
    """One row per invoice issued on or before month_end, in the order the invoices are
    given, with what's been paid against it. Finance runs it on the last day of the month."""
    rows = []
    for invoice in invoices:
        if invoice.issued_on > month_end:
            continue
        paid = 0
        for payment in payments:
            if payment.invoice_id != invoice.id:
                continue
            if payment.status is PaymentStatus.FAILED:
                continue
            if payment.paid_on > month_end:
                continue  # it'll be in next month's report
            if payment.kind is PaymentKind.REFUND:
                paid -= payment.amount_cents
            else:
                paid += payment.amount_cents
        rows.append(ReportRow(invoice.id, invoice.subscriber_id, invoice.total_cents, paid))
    return rows


def total_outstanding(rows: list[ReportRow]) -> int:
    return sum(row.outstanding_cents for row in rows)
data/price_sheet.csv 4 lines
code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
tests/test_existing.py 111 lines
"""What already works. These pass now; keep them passing."""

import unittest
from datetime import date

from cakeclub.billing import plan_amount, run_billing, sign_up
from cakeclub.catalog import Catalog, UnknownPlanError, load_price_sheet, menu_export
from cakeclub.models import Interval, Invoice, InvoiceLine, Payment, PaymentKind, PaymentStatus, Plan
from cakeclub.money import format_cents, percent_off, to_cents
from cakeclub.reports import ReportRow, month_end_report, total_outstanding

PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""


class TestMoney(unittest.TestCase):
    def test_to_cents(self):
        self.assertEqual(to_cents("32.00"), 3200)
        self.assertEqual(to_cents(19.5), 1950)
        self.assertEqual(to_cents("0.005"), 1)

    def test_format_cents(self):
        self.assertEqual(format_cents(3200), "$32.00")
        self.assertEqual(format_cents(3200000), "$32,000.00")
        self.assertEqual(format_cents(-150), "-$1.50")
        self.assertEqual(format_cents(7), "$0.07")

    def test_percent_off_rounds_down(self):
        self.assertEqual(percent_off(1999, 10), 199)
        with self.assertRaises(ValueError):
            percent_off(1000, 120)


class TestCatalog(unittest.TestCase):
    def test_price_sheet_is_read_into_cents_in_menu_order(self):
        catalog = load_price_sheet(PRICE_SHEET)
        self.assertEqual([plan.code for plan in catalog.plans()], ["classic", "deluxe", "mini"])
        self.assertEqual(catalog.get("classic"), Plan("classic", "Classic box", 3200, 1))
        self.assertEqual(catalog.get("deluxe").boxes_per_month, 2)

    def test_unknown_plan(self):
        with self.assertRaises(UnknownPlanError):
            load_price_sheet(PRICE_SHEET).get("jumbo")

    def test_duplicate_codes_are_refused(self):
        with self.assertRaises(ValueError):
            Catalog([Plan("a", "A", 100), Plan("a", "A again", 200)])

    def test_menu_export(self):
        self.assertEqual(menu_export(load_price_sheet(PRICE_SHEET)),
                         "Classic box - $32.00 a month\nDeluxe box - $54.00 a month\nMini box - $19.00 a month")


class TestBilling(unittest.TestCase):
    def setUp(self):
        self.catalog = load_price_sheet(PRICE_SHEET)

    def test_monthly_price(self):
        self.assertEqual(plan_amount(self.catalog.get("classic"), Interval.MONTH), 3200)

    def test_sign_up(self):
        sub = sign_up(self.catalog, "s1", " Ana@Example.com ", date(2027, 3, 4), "deluxe")
        self.assertEqual((sub.email, sub.plan_code, sub.interval), ("ana@example.com", "deluxe", Interval.MONTH))
        self.assertEqual(sub.next_bill_on, date(2027, 3, 4))

    def test_sign_up_without_a_plan_gets_the_first_plan_on_the_menu(self):
        self.assertEqual(sign_up(self.catalog, "s1", "ben@example.com", date(2027, 3, 4)).plan_code, "classic")

    def test_a_monthly_subscriber_is_billed_on_signup_and_then_monthly(self):
        sub = sign_up(self.catalog, "s1", "cy@example.com", date(2027, 1, 15), "classic")
        invoices = run_billing([sub], self.catalog, date(2027, 3, 20))
        self.assertEqual([inv.issued_on for inv in invoices], [date(2027, 1, 15), date(2027, 2, 15), date(2027, 3, 15)])
        self.assertEqual([inv.total_cents for inv in invoices], [3200, 3200, 3200])
        self.assertEqual(invoices[0].lines, [InvoiceLine("Classic box, monthly ($32.00)", 3200)])
        self.assertEqual(invoices[0].id, "INV-s1-20270115")
        self.assertEqual(sub.next_bill_on, date(2027, 4, 15))

    def test_a_second_run_on_the_same_day_bills_nothing(self):
        sub = sign_up(self.catalog, "s1", "di@example.com", date(2027, 5, 2), "mini")
        self.assertEqual(len(run_billing([sub], self.catalog, date(2027, 5, 2))), 1)
        self.assertEqual(run_billing([sub], self.catalog, date(2027, 5, 2)), [])

    def test_inactive_subscribers_are_not_billed(self):
        sub = sign_up(self.catalog, "s1", "ed@example.com", date(2027, 5, 2), "mini")
        sub.active = False
        self.assertEqual(run_billing([sub], self.catalog, date(2027, 9, 1)), [])


class TestMonthEndReport(unittest.TestCase):
    def test_a_small_month(self):
        invoices = [
            Invoice("i1", "s1", date(2027, 6, 3), [InvoiceLine("Classic box, monthly ($32.00)", 3200)]),
            Invoice("i2", "s2", date(2027, 6, 10), [InvoiceLine("Mini box, monthly ($19.00)", 1900)]),
            Invoice("i3", "s3", date(2027, 7, 1), [InvoiceLine("Mini box, monthly ($19.00)", 1900)]),
        ]
        payments = [
            Payment("p1", "i1", 3200, date(2027, 6, 3)),
            Payment("p2", "i2", 1900, date(2027, 6, 10), status=PaymentStatus.FAILED),
            Payment("p3", "i2", 1000, date(2027, 6, 12)),
            Payment("p4", "i1", 500, date(2027, 6, 20), kind=PaymentKind.REFUND),
        ]
        rows = month_end_report(invoices, payments, date(2027, 6, 30))
        self.assertEqual(rows, [ReportRow("i1", "s1", 3200, 2700), ReportRow("i2", "s2", 1900, 1000)])
        self.assertEqual(total_outstanding(rows), 500 + 900)


if __name__ == "__main__":
    unittest.main()
tests/test_stage1.py 40 lines
"""Bug 1: annual subscribers are charged 100 times too much."""

import unittest
from datetime import date

from cakeclub.billing import plan_amount, run_billing, sign_up
from cakeclub.catalog import load_price_sheet
from cakeclub.models import Interval
from cakeclub.money import format_cents

PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""


class TestAnnualPrice(unittest.TestCase):
    def setUp(self):
        self.catalog = load_price_sheet(PRICE_SHEET)

    def test_the_reported_case(self):
        sub = sign_up(self.catalog, "s1", "fay@example.com", date(2027, 2, 1), "classic", Interval.YEAR)
        [invoice] = run_billing([sub], self.catalog, date(2027, 2, 1))
        self.assertEqual(format_cents(invoice.total_cents), "$320.00", "ten months of $32.00")

    def test_every_plan_is_ten_months_price(self):
        for code, annual in [("classic", 32000), ("deluxe", 54000), ("mini", 19000)]:
            with self.subTest(plan=code):
                self.assertEqual(plan_amount(self.catalog.get(code), Interval.YEAR), annual)

    def test_the_next_year_costs_the_same(self):
        sub = sign_up(self.catalog, "s1", "gus@example.com", date(2027, 2, 1), "mini", Interval.YEAR)
        invoices = run_billing([sub], self.catalog, date(2028, 2, 1))
        self.assertEqual([inv.issued_on for inv in invoices], [date(2027, 2, 1), date(2028, 2, 1)])
        self.assertEqual([inv.total_cents for inv in invoices], [19000, 19000])


if __name__ == "__main__":
    unittest.main()
tests/test_stage2.py 45 lines
"""Bug 2: billing dates drift after a short month."""

import unittest
from datetime import date

from cakeclub.billing import run_billing, sign_up
from cakeclub.catalog import load_price_sheet
from cakeclub.models import Interval

PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""


class TestBillingDates(unittest.TestCase):
    def setUp(self):
        self.catalog = load_price_sheet(PRICE_SHEET)

    def billing_dates(self, started_on, until):
        sub = sign_up(self.catalog, "s1", "hal@example.com", started_on, "classic", Interval.MONTH)
        return [invoice.issued_on for invoice in run_billing([sub], self.catalog, until)], sub

    def test_the_reported_case(self):
        dates, sub = self.billing_dates(date(2027, 1, 31), date(2027, 4, 30))
        self.assertEqual(dates, [date(2027, 1, 31), date(2027, 2, 28), date(2027, 3, 31), date(2027, 4, 30)])
        self.assertEqual(sub.next_bill_on, date(2027, 5, 31))

    def test_one_run_a_day_gives_the_same_dates(self):
        sub = sign_up(self.catalog, "s1", "ida@example.com", date(2027, 1, 31), "classic")
        billed = []
        day = date(2027, 1, 31)
        while day <= date(2027, 3, 31):
            billed += [invoice.issued_on for invoice in run_billing([sub], self.catalog, day)]
            day = date.fromordinal(day.toordinal() + 1)
        self.assertEqual(billed, [date(2027, 1, 31), date(2027, 2, 28), date(2027, 3, 31)])

    def test_mid_month_is_unchanged(self):
        dates, sub = self.billing_dates(date(2027, 1, 15), date(2027, 3, 15))
        self.assertEqual(dates, [date(2027, 1, 15), date(2027, 2, 15), date(2027, 3, 15)])


if __name__ == "__main__":
    unittest.main()
tests/test_stage3.py 32 lines
"""Bug 3: new signups get the wrong default plan."""

import unittest
from datetime import date

from cakeclub.billing import sign_up
from cakeclub.catalog import load_price_sheet
from cakeclub.pages import pricing_page

PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""


class TestDefaultPlan(unittest.TestCase):
    def setUp(self):
        self.catalog = load_price_sheet(PRICE_SHEET)

    def test_the_reported_case(self):
        pricing_page(self.catalog)  # someone looked at the Plans page first
        sub = sign_up(self.catalog, "s1", "jo@example.com", date(2027, 11, 20))
        self.assertEqual(sub.plan_code, "classic", "the first plan on the menu is the Classic box")

    def test_the_plans_page_is_still_cheapest_first(self):
        names = [line.split(":")[0] for line in pricing_page(self.catalog).splitlines()[1:]]
        self.assertEqual(names, ["Mini box", "Classic box", "Deluxe box"])


if __name__ == "__main__":
    unittest.main()
tests/test_stage4.py 62 lines
"""Bug 4: the month-end report never finishes."""

import random
import unittest
from datetime import date

from cakeclub.models import Invoice, InvoiceLine, Payment, PaymentKind, PaymentStatus
from cakeclub.reports import month_end_report, total_outstanding


class TookTooLong(Exception):
    pass


class MeteredPayment:
    """Stands in for a Payment and counts how many times anything looks up which invoice it's
    for. Past the limit it gives up, the way finance's 15-minute job timeout does."""

    def __init__(self, payment, meter):
        self._payment = payment
        self._meter = meter

    @property
    def invoice_id(self):
        self._meter["lookups"] += 1
        if self._meter["lookups"] > self._meter["limit"]:
            raise TookTooLong(f"more than {self._meter['limit']:,} payment lookups: this won't finish on a real month")
        return self._payment.invoice_id

    def __getattr__(self, name):
        return getattr(self._payment, name)


def a_busy_month():
    """20,000 invoices in November and 30,000 payments: every invoice paid in full, 5,000 of
    them after a failed first try, and 5,000 with a $5.00 refund."""
    invoices, payments = [], []
    for n in range(20_000):
        invoice_id = f"INV-{n:05d}"
        invoices.append(Invoice(invoice_id, f"s{n}", date(2027, 11, 1 + n % 30),
                                [InvoiceLine("Classic box, monthly ($32.00)", 3200)]))
        if n < 5_000:
            payments.append(Payment(f"f{n}", invoice_id, 3200, date(2027, 11, 1 + n % 30), status=PaymentStatus.FAILED))
        payments.append(Payment(f"p{n}", invoice_id, 3200, date(2027, 11, 1 + n % 30)))
        if 5_000 <= n < 10_000:
            payments.append(Payment(f"r{n}", invoice_id, 500, date(2027, 11, 30), kind=PaymentKind.REFUND))
    random.Random(4).shuffle(payments)
    return invoices, payments


class TestMonthEndReportScales(unittest.TestCase):
    def test_the_reported_case(self):
        invoices, payments = a_busy_month()
        meter = {"lookups": 0, "limit": 50 * len(payments)}
        rows = month_end_report(invoices, [MeteredPayment(p, meter) for p in payments], date(2027, 11, 30))
        self.assertEqual(len(rows), 20_000)
        self.assertEqual([row.invoice_id for row in rows[:3]], ["INV-00000", "INV-00001", "INV-00002"])
        self.assertEqual(total_outstanding(rows), 5_000 * 500)


if __name__ == "__main__":
    unittest.main()

Download the starter repo, or open it in the browser workspace (beta).

Done? Run the hidden tests: in the workspace, choose Hidden tests in the Run menu. Working locally? Download the hidden tests and unzip them where you unzipped the starter, which adds a hidden_tests folder to the repo. Try not to read them. Then, in the repo's folder, run python3 -m unittest discover -s hidden_tests.

Out of time, or passing the hidden tests too? Download the reference solution (spoilers) and compare it with yours.

More AI coding interview practice

Existing codebase Hard · 75 min · 4 stages

Bakery Order Service

Pick up four tickets in a working bakery order service: fix a stock bug, add coupon codes, make the dashboard queries scale, then add cancellations. Practice reading, debugging and extending code you didn't write, with an AI assistant at your side.

Same format as
  • Meta · AI-enabled coding round AI expected
  • Google · Code comprehension round (pilot) AI allowed
  • Ramp · AI-assisted coding round AI expected
Bug squash Medium · 60 min · 4 stages

Delivery Scheduler Bug Squash

Four bug reports, written as symptoms, in a small cake delivery scheduler. Find and fix each root cause, and practice not accepting an AI's plausible-but-wrong fix.

Same format as
  • Stripe · Bug squash (bug bash) round No AI unless told
  • Google · Code comprehension round (pilot) AI allowed
Progressive build Medium · 75 min · 4 stages

Cake Database (Progressive Build)

Build the bakery's in-memory order database in four levels, from set/get to TTLs and backup/restore. The design you pick in level 1 decides how painful level 4 is.

Same format as
  • Anthropic · Coding assessment No AI
  • OpenAI · Technical screen AI depends on the round
  • Stripe · Practical coding round No AI unless told
Existing codebase Expert · 90 min · 3 stages

Bakehouse Production Planner

Three tickets in a central kitchen's production planner, about 1,500 lines of Python with its tests: fix a wrong prep list, write the store room's pick lists, fit in a change request from the food safety inspector, then plan all of December in one run without changing a single number.

Expert. Longer and harder than most real rounds: a bigger codebase, a change request partway through, a speed limit and hidden tests. Expect not to finish the first time, and if you haven't done a hard problem yet, start with one of those.

Same format as
  • Meta · AI-enabled coding round AI expected
  • Google · Code comprehension round (pilot) AI allowed

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 5, 2026

. . .