Debugging
In both tasks the code is already written, the tests fail, and a bug report says what the team sees. The bugs are classic Python ones: a mutable default argument, an end that should be excluded, money in float, an except that catches too much. So they test whether you know the language and can read a failing test. They build on Testing and complexity and Money and Decimal.
D02. Subscription report
Section titled “D02. Subscription report”This is a debugging task: the code is already written, but the report is wrong. The product team says the number of active subscribers is too high, it does not change when they pass a different list of transactions, and revenue sometimes shows numbers like 10.290000000000001.
active_at should count, per product, the paid subscriptions active at moment: start <= moment < end, not a trial, not a test purchase, not promo, not refunded by that moment. revenue_by_product should be the sum of revenue_usd per product, without test purchases, exact to the cent, as Decimal.
Click Check, read which tests fail, find each bug and say it out loud: "The bug is …, because …". Then fix it.
a subscription that ended exactly at moment should not be active
active now: {'a': 1} should be {}
revenue of 0.10 × 3: {'a': 0.30000000000000004} should be {'a': Decimal('0.30')}Full statement (as in the task file)
BUG REPORT (from the product team)
"Active subscriber numbers are a bit too high, and they do not change when we pass a different list of transactions in the same process. Revenue sometimes shows numbers like 10.290000000000001 in the export."
What the functions SHOULD do (the tests check this):
- active_at(transactions, moment) -> {product_id: count} of PAID subscriptions active at `moment`: start_time <= moment < end_time (end excluded), not a trial, not a test purchase, not 'promo', and not refunded at or before `moment`.
- revenue_by_product(transactions) -> {product_id: Decimal}: SUM(revenue_usd) per product, test purchases excluded, exact to the cent (Decimal, never float).Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Is a period that ends exactly at moment still active?
No, the end is excluded.
Do we need the cache?
Only if it is correct. If you remove it, say why it was wrong.
Which fields mark promo and refunded transactions?
t["channel"] == "promo"; t["refunded_at"] is a datetime or None.
def active_at(transactions, moment, _cache={}):
if moment in _cache:
return _cache[moment]
counts = {}
for t in transactions:
if t["is_trial"] or t["is_test"]:
continue
if t["start_time"] <= moment <= t["end_time"]:
counts[t["product_id"]] = counts.get(t["product_id"], 0) + 1
_cache[moment] = counts
return counts
def revenue_by_product(transactions):
total = {}
for t in transactions:
if t["is_test"]:
continue
total[t["product_id"]] = total.get(t["product_id"], 0.0) + float(t["revenue_usd"])
return total
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Start with the failure that says the result does not change for a different list: what could survive from one call to the next? Fix that first, and the other failures will make more sense.
Say it: A mutable default cache, an inclusive end, missing promo and refund filters, and float money.
Reference solution
# Bugs: (1) mutable default `_cache={}` lives between calls and ignores `transactions` -> stale numbers;# (2) `<= end_time` — the period is [start, end), end excluded;# (3) promo grants and refunds were not excluded;# (4) money in float: 0.1 + 0.2 != 0.3 -> keep Decimal.from decimal import Decimal
def active_at(transactions, moment): counts = {} for t in transactions: if t["is_trial"] or t["is_test"] or t["channel"] == "promo": continue if t["refunded_at"] is not None and t["refunded_at"] <= moment: continue if t["start_time"] <= moment < t["end_time"]: counts[t["product_id"]] = counts.get(t["product_id"], 0) + 1 return counts
def revenue_by_product(transactions): total = {} for t in transactions: if t["is_test"]: continue total[t["product_id"]] = total.get(t["product_id"], Decimal("0")) + t["revenue_usd"] return totalWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. The product team sees active numbers that are too high and results that “stick”. These are the usual signs of shared state and wrong boundaries.
The bugs.
- The cache in
active_atis a mutable default argument._cache={}is created once, lives between calls, and its key ignorestransactions. Remove it; do not try to repair it. <= t["end_time"]: the end of the period is not included, so it must be<.- Promo access and refunds at or before
momentare not excluded. revenue_by_productadds money in float: 0.10 + 0.20 + 9.99 gives10.290000000000001. KeepDecimaland add it up exactly. Rounding the float at the end would only hide the error, and the result would still be a float.
How to find them.
- Read the failure messages. “Does not change for a different list” means state between calls. A float where a
Decimalwas expected means float money. - Fix the cache first. While it is there, it returns the result of an earlier call, and the other failures are misleading. In one Check run,
test_promo_and_refundsshows{'a': 1}, left over from the previous test, instead of the real{'a': 3, 'b': 1}.
Complexity. One pass, O(n) per call. The cache was never worth it: a correct one would need the whole list of transactions in its key.
D03. Webhook delivery to merchants
Section titled “D03. Webhook delivery to merchants”This is a debugging task: we deliver webhooks to our merchants' servers, and the code is already written. Support says merchant A never got some webhooks, even after their endpoint was back up. Merchant B got none at all on a worker that had just served merchant A. And a bug in one payload made the worker sleep for seconds instead of failing fast.
How it should work: deliver events in created_at order. Skip ids that are in seen, and add an id to seen only AFTER a successful send. If the caller does not pass seen, every call starts with an empty set. On TemporaryError, retry — at most max_attempts sends, waiting 1, 2, 4… seconds, and no wait after the last failure; such an event stays out of seen. Any other error goes up immediately. Return the ids delivered in this call.
Click Check, find each bug, say it out loud and fix it.
events e2 (t=2), e1 (t=1); e1 fails twice with TemporaryError, then succeeds → ['e1', 'e2'], waits [1.0, 2.0] a second call for another merchant, without seen → ['e1', 'e2'] again
Full statement (as in the task file)
BUG REPORT (from support) "Merchant A says some webhooks never arrived, even after the endpoint was back up. Merchant B got NONE of their webhooks on a worker that had just served merchant A. And a payload bug made the worker sleep for seconds instead of failing fast." What deliver_all SHOULD do (the tests check this): - Deliver events in created_at order. `seen` holds ids that were already delivered; the caller owns it. If the caller does not pass `seen`, every call starts with an empty set. - An id in `seen` is skipped. An id is added to `seen` only AFTER a successful send. - send(event) may raise TemporaryError -> retry, at most `max_attempts` sends in total for that event. Before retry k (k = 1, 2, ...) wait base_delay * 2 ** (k - 1). Do not wait after the final failure. - An event that still fails is skipped for now (not in `seen`), so the next run tries it again. - Any other exception from send is a bug in our payload: let it propagate immediately, no retries. - Return the list of ids delivered in this call.
Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Who owns seen?
The caller. If it is not passed, every call starts with an empty set.
import time
class TemporaryError(Exception):
pass
def deliver_all(events, send, seen=set(), max_attempts=3, base_delay=1.0, sleep=time.sleep):
delivered = []
for event in sorted(events, key=lambda e: e["created_at"]):
if event["id"] in seen:
continue
seen.add(event["id"])
for attempt in range(max_attempts):
try:
send(event)
delivered.append(event["id"])
break
except Exception:
sleep(base_delay * 2 ** attempt)
return delivered
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Start with the test that calls deliver_all twice without seen: what in the signature lives longer than one call? Then follow one event that fails, line by line.
Say it: The default set is shared between calls, the id is marked before success, every exception is retried, and it sleeps after the final failure.
Reference solution
# Bugs: (1) `seen=set()` is created once and shared by every call that does not pass it# -> a worker that served merchant A then skips merchant B's ids that A already got;# (2) the id is added to `seen` before the send succeeds -> failed events are never retried;# (3) `except Exception` also retries payload bugs -> catch only TemporaryError;# (4) it sleeps after the last failed attempt as well.import time
class TemporaryError(Exception): pass
def deliver_all(events, send, seen=None, max_attempts=3, base_delay=1.0, sleep=time.sleep): seen = set() if seen is None else seen delivered = [] for event in sorted(events, key=lambda e: e["created_at"]): if event["id"] in seen: continue for attempt in range(1, max_attempts + 1): try: send(event) except TemporaryError: if attempt < max_attempts: sleep(base_delay * 2 ** (attempt - 1)) continue seen.add(event["id"]) delivered.append(event["id"]) break return deliveredWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. We deliver webhooks to our merchants’ servers. Some events are lost, and a worker that has just served one merchant sends nothing to the next one.
The bugs.
seen=set()as a default is created once and shared by every call that does not passseen. The next call on the same worker then skips ids that were delivered for another merchant. Useseen=Noneand create the set inside the function.- The id is added to
seenbefore the send succeeds, so an event that failed is never retried. except Exceptionalso retries bugs in our payload. Catch onlyTemporaryErrorand let everything else go up.- It sleeps after the final failure as well. Wait only when another attempt follows.
How to find them. The failing tests point at the bugs one by one:
test_fresh_calls_do_not_share_stategets[]instead of['x']: bug 1.- The waits are
[1.0, 2.0, 1.0, 2.0, 4.0]instead of[1.0, 2.0, 1.0, 2.0]: bug 4. ValueErroris not raised for the payload bug: bug 3.- After the waits are fixed, the same retry test shows bug 2:
bis inseen, although it was never delivered.
Complexity. O(n log n) for the sort by created_at, plus at most max_attempts sends per event.
In production. seen lives in a database or a queue with acknowledgements, not in a Python set. The retry delays usually get random jitter, so many workers do not retry at the same moment.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.