Fix the round trip count for ORM loading
Your task
A latency regression came from an N+1 query: a lazy-loaded ORM relation ran 1 query for a list and then 1 more for each of its N items. An AI drafted an analogy for your PM: "a separate trip to the store for every item". Before you send it, you check the analogy against real round trip counts. You also check it does not suggest a fix that is not one, like a bigger database.
An assistant wrote count_query_round_trips(strategy, item_count, batch_size). It is in the editor. It has a bug. Find it and fix it.
Input and output:
strategy: the name of an ORM loading strategy.item_count: how many items the list holds.batch_size: how many items one batched query covers.- Return the number of database round trips, or -1 when
strategyis not a loading strategy.
Rules the tests check:
- Trim whitespace from
strategyand lowercase it before matching. - A negative
item_countcounts as 0. "lazy": 1 query for the list, plus 1 per item."eager": 1 query for the list, plus 1 query that loads every item's children at once. With 0 items, that second query is skipped."join": 1 query in total."batched": 1 query for the list, plus 1 per batch ofbatch_sizeitems, rounding up. Abatch_sizeof 0 or less counts as 1. With 0 items there are no batches.- Any other strategy, such as
"scale_up_db", returns -1.
Examples
count_query_round_trips(strategy: str, item_count: int, batch_size: int) -> intExample 1
Input
count_query_round_trips("lazy", 50, 25)Output
51Example 2
Input
count_query_round_trips("eager", 50, 25)Output
2Example 3
Input
count_query_round_trips("batched", 50, 20)Output
4