Fix the cursor loop in a charges client

Review the AI's codeEasy12 minStripe style

Your task

An AI wrote a client that pulls every charge from a cursor-paginated API. Its loop repeated the first request and never advanced the cursor, so large accounts lost records or the loop never ended. The new loop follows the cursor and must also stop when a misbehaving server sends it back to a page it has already read.

An assistant wrote fetch_all_charges(pages, max_pages), which walks a model of the API. It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • pages: the API's pages, each written cursor;items;next_cursor. items is a comma separated list of charge ids. An empty next_cursor means there are no more pages.
  • max_pages: the most pages the client may request.
  • Return the charge ids collected, in order.

Rules the tests check:

  • The first request uses the cursor start. Make at most max_pages requests.
  • A request is answered by the first entry in pages that splits on ; into exactly 3 parts and whose first part equals the cursor. If no entry answers, stop.
  • Collect the page's charge ids in order, skipping empty ones.
  • Then stop if the next cursor is empty, or if it is any cursor already requested, the current one included. Otherwise request the next cursor.

Examples

fetch_all_charges(pages: list[str], max_pages: int) -> list[str]
Example 1
Inputfetch_all_charges(["start;c1,c2;p2", "p2;c3,c4;p3", "p3;c5;"], 10)
Output["c1", "c2", "c3", "c4", "c5"]
Example 2
Inputfetch_all_charges(["start;c1,c2;start"], 10)
Output["c1", "c2"]
Example 3
Inputfetch_all_charges([], 10)
Output[]