Debug a codebase then propose long-term fixes
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Cursor's onsite project round. It tests debugging, refactoring and code review.
You inherit a small order service: an inventory that holds stock for orders, a pricing module, and the order service that ties them together. Support tickets say stock "disappears", some order totals are a cent off, page 1 of the order list skips orders, and a cart hold sometimes never expires. Find and fix the defects, add tests that would have caught them, then write up the structural changes that stop this class of bug coming back. You have about 60 minutes and may run code.
Prices are integer cents. A discount is rounded half up to the cent. Pages are numbered from 1.
class OutOfStock(Exception):
pass
class Inventory:
def __init__(self, stock=None):
self.stock = dict(stock or {}) # sku -> units on the shelf
self.reserved = {} # order_id -> {sku: qty}
def available(self, sku):
return self.stock.get(sku, 0)
def reserve(self, order_id, items):
"""Hold every (sku, qty) in `items` for one order, or none of them."""
held = {}
for sku, qty in items.items():
if self.stock.get(sku, 0) < qty:
raise OutOfStock(sku)
self.stock[sku] -= qty
held[sku] = qty
self.reserved[order_id] = held
def release(self, order_id):
for sku, qty in self.reserved.pop(order_id, {}).items():
self.stock[sku] += qty
import functools
import time
def order_total(lines, discount_pct=0):
"""Total in integer cents. `lines` is [(price_cents, qty)].
The discount is rounded half up to the cent, then taken off the subtotal."""
subtotal = sum(price * qty for price, qty in lines)
return int(subtotal * (1 - discount_pct / 100))
def ttl_cache(seconds, clock=time.monotonic):
"""Memoize a function's results for `seconds`."""
def decorate(fn):
store = {}
@functools.wraps(fn)
def wrapper(*args, **kwargs):
key = args
hit = store.get(key)
if hit is not None and clock() - hit[1] < seconds:
return hit[0]
value = fn(*args, **kwargs)
store[key] = (value, clock())
return value
return wrapper
return decorate
import time
from inventory import Inventory
from pricing import order_total
class OrderService:
def __init__(self, inventory: Inventory, payments):
self.inventory = inventory
self.payments = payments # has charge(order_id, cents); may raise
self.orders = {}
def place(self, order_id, lines, discount_pct=0, tags=[]):
"""lines: [(sku, qty, price_cents)]. Reserve stock, charge, record."""
tags.append("web")
self.inventory.reserve(order_id, {sku: qty for sku, qty, _ in lines})
total = order_total([(price, qty) for _, qty, price in lines], discount_pct)
self.payments.charge(order_id, total)
self.orders[order_id] = {"status": "paid", "total": total, "tags": tags, "created_at": time.time()}
return self.orders[order_id]
def hold(self, order_id, items, now=None):
"""Reserve stock for a cart without paying yet."""
self.inventory.reserve(order_id, items)
self.orders[order_id] = {"status": "pending", "tags": [], "created_at": time.time() if now is None else now}
def expire_holds(self, max_age_s, now=time.time()):
"""Drop pending holds older than max_age_s and put their stock back."""
for order_id, order in self.orders.items():
if order["status"] == "pending" and now - order["created_at"] > max_age_s:
self.inventory.release(order_id)
del self.orders[order_id]
def list_orders(self, page, page_size):
"""Order ids, sorted; pages are numbered from 1."""
ids = sorted(self.orders)
start = page * page_size
return ids[start:start + page_size]
Clarifying questions
-
reservesays "all of them or none". When the payment fails, should the held stock go back as well? - Is half-up rounding applied to the discount amount, with the subtotal minus that discount as the total?
- Is the service single-threaded, or must it also be safe under concurrent requests?
- May I change public signatures, or only internals?
What a strong answer covers
- Works ticket by ticket: a failing test that reproduces each symptom, then the smallest fix, keeping the test.
- Looks across all three files, including defects no ticket names: stock taken for earlier items when a later one is out of stock, stock left held when the charge raises, Python defaults evaluated once at definition time, a dict changed while it is being iterated, float maths and truncation on cents, the 1-based page offset, and a cache key that ignores keyword arguments.
- Keeps money in integers and rounds half up explicitly, checked with totals that land exactly on half a cent.
- Passes the clock in instead of reading wall time, so expiry can be tested.
- The write-up names structural changes: a money type, all-or-nothing reserve, charge and record steps (with compensation when one fails), injected clocks, lint rules for mutable and call defaults, and property tests that stock is never created or lost.
Follow-ups
- Two requests reserve the last unit at the same moment: what changes?
- The payment provider times out after charging: how do you make
placesafe to retry? - Some customers were already charged a cent wrong: how do you find and fix those orders?
Where it's asked
- Cursor · Onsite projectOne or two days at the office building a real project with the team, in a slice of Cursor's codebase
What it tests
debugging · refactoring · code review
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
