Mode: Debugging.
Python 3.11, PyMongo 4.11.3, and MongoDB 8.0.
Stockroom is a private inventory API. Operators see successful creates disappear, stale update responses and cross-account access. Repair the Python service while retaining the real MongoDB persistence layer.
Edit service.py and REFLECTION.essay. Keep the public names, signatures and fixed files unchanged. You may add helper modules and your own regression tests. The fixed model.py, HTTP adapter and application can be inspected.
InventoryService(collection)
InventoryService.handle(method, path, user, body=None) -> Response
collection is an initialized PyMongo collection. handle accepts a parsed body: a dictionary for valid create/update requests. Invalid shapes return the documented error. Response.status is an integer; Response.body is an item dictionary, a list of item dictionaries, an error dictionary, or None for deletion. Returned quantity and version values are Python integers.
Numeric inputs may be int, finite integral float, or exact integral decimal.Decimal, within their bounds. Strings, booleans and None are never numbers. The fixed HTTP parser preserves fractional JSON numbers as Decimal, so a value such as 3.0000000000000001 cannot silently round into a valid integer. The supplied helpers implement ECMAScript whitespace and UTF-16 length rules.
- Use the pinned driver and an actual MongoDB server. Do not replace persistence with an in-memory collection.
initialize_itemscreates the collection's validation rules and unique index before returning it. Pass that initialized collection into the service.- Set
MONGODB_URIif the server is not atmongodb://127.0.0.1:27017. - Tests create unique
stockroom_test_*databases and drop only those databases, even if the URI contains a database name. - The demo application uses
stockroom_localby default.MONGODB_DATABASEchanges the demo database;PORTchanges its default port, 8080. No credentials or.envare supplied.
- First require a nonblank string user, otherwise return
401 unauthorized. Preserve the user's value exactly, including surrounding spaces. - Routes are
/itemsand/items/{id}. Unknown paths return404 not_found. - An item ID must be exactly 24 hexadecimal characters, otherwise return
400 invalid_id. Accept either letter case; returned IDs are lowercase. - Unsupported methods on valid paths return
405 method_not_allowed. Validate identity, route and ID in that order before dispatching a method. - Every error body is a dictionary containing exactly
{"error": code}.
POST /itemsrequires exactly{sku, name, quantity}.skuis a case-sensitive string consisting of 1 to 24 uppercase ASCII letters, digits or hyphens.nameis a string with trimmed length 1 to 80 UTF-16 code units. Use the suppliedtrimrules for names and blank-identity checks. Store the trimmed name.quantityis an integer number from 0 through 1000000. Reject invalid values with400 invalid_input.- Persist before returning 201 with exactly
{id, owner, sku, name, quantity, version}. Generate the ObjectId, preserve the authenticated owner and set version to 1. Do not accept caller-supplied owner, id or version.
GET /itemsreturns 200 and this user's documents sorted by sku ascending, then id ascending. An empty list is valid.GET /items/{id}returns 200 and one document.- Missing items and items owned by another user both return
404 item_not_found. DELETE /items/{id}deletes only the owned item and returnsResponse(204, None). Repeating the deletion returns 404.
PATCH /items/{id}requires an integer version from 1 through9223372036854775806and at least one of name or quantity. No other fields are allowed. The upper bound leaves room for the increment.- Validate the entire payload, including quantity bounds and trimmed name length, before looking up the owned item. Invalid input returns
400 invalid_input; a missing or foreign item returns404 item_not_found; a version mismatch returns409 version_conflict. - Atomically update the matching owner, ID and version. Return 200 and the updated document, with version incremented by one even when the supplied values are unchanged.
- Never change owner, sku or id. Every failed update leaves all fields and the version unchanged.
- Concurrent valid patches using one version allow exactly one success, including requests handled by separate service instances. Concurrent deletion during a patch is outside the exercise's workload.
- The fixed compound unique index enforces
(owner, sku). A duplicate creation returns409 sku_conflictwithout adding a document, including concurrent calls. Another owner may use the same sku. - Database duplicate-key errors use code 11000. Schema validation errors use code 121 and map to
400 invalid_input. Unexpected storage errors map to503 storage_unavailable. - Return JSON-serializable values and do not expose exception details.
- The supplied server reads
X-User-ID, parses JSON and delegates tohandle. Malformed JSON returns400 invalid_json; query strings do not affect routing. - A 204 response has an empty body. The server binds to the container interfaces so the IDE can forward its port.
- The model, server transport, public tests, Python dependency configuration and setup scripts are fixed. Implement the repair in the service and any helpers you add.
- Authenticate requests and validate payloads.
- Persist new documents and return database query results.
- Scope reads, updates and deletes to the owner.
- Apply version checks and increments in the same database operation.
- Map storage errors and verify the HTTP responses.
75 minutes, including investigation, implementation, regression testing and the reflection answers.
Click Run in the IDE to run the public tests. The starter imports successfully but some public tests fail intentionally. After changes, check the test results as well as whether the server starts. Public tests cover part of the contract; implement every requirement above. Tests use temporary databases and time limits.
MongoDB 8.0 runs in the environment at mongodb://127.0.0.1:27017. Fill in each question's answer field in REFLECTION.essay; discuss the proposed extensions without implementing them.
Run does not start the demo server, and the tests do not need it.
# Start the demo server:
bash .theia/run_app.shWith a correctly implemented service and an initialized collection:
created = service.handle(
"POST", "/items", "alice", {"sku": "BOOK-1", "name": "Book", "quantity": 3}
)
assert created.status == 201
item = created.body
assert item["owner"] == "alice"
assert item["quantity"] == 3
assert item["version"] == 1
assert service.handle("GET", "/items/" + item["id"], "alice").body == item