Skip to content

fix: iterate past empty pages that still carry a next_page_token - #3435

Open
yqecea wants to merge 1 commit into
googleapis:mainfrom
yqecea:fix-pager-empty-pages
Open

yqecea wants to merge 1 commit into
googleapis:mainfrom
yqecea:fix-pager-empty-pages

Conversation

@yqecea

@yqecea yqecea commented Nov 28, 2026

Copy link
Copy Markdown

Summary

Pager and AsyncPager crashed with IndexError: list index out of range when a list page came back empty but the response still carried a next_page_token, so items on later pages were silently unreachable.

Google list APIs are allowed to return fewer items than page_size, including zero, before the end of the collection (AIP-158). This is common with filters, where one scanned page can match nothing.

Root cause

__next__/__anext__ fetched the next page once when the current page was exhausted, then indexed into it unconditionally:

if self._idx >= len(self):
    self.next_page()  # new page may still be empty, with another token
item = self.page[self._idx]  # IndexError on an empty page

Fix

Loop instead of a single fetch: keep pulling pages while the current one is exhausted and a next_page_token exists. Iteration still stops when a response arrives without a token.

Tests

New google/genai/tests/pagers/test_pagers.py, reproducing the exact scenario from the issue with token-keyed mock pages:

  • test_pager_iterates_past_empty_page: sync iteration yields ['files/a', 'files/b'] across the empty middle page
  • test_pager_stops_after_last_empty_page: iteration still terminates when the empty page is the last one
  • test_async_pager_iterates_past_empty_page: same for AsyncPager

Red-green verified: the sync test fails with IndexError on unpatched main and all 3 pass with the fix.

Fixes #3429

Pager and AsyncPager raised IndexError when a page came back empty but
the response still had a next_page_token, so items on later pages were
never returned. List APIs may return fewer items than page_size,
including zero, before the end of the collection (AIP-158), which is
common with filtered list calls.

Fixes googleapis#3429
@google-cla

google-cla Bot commented Nov 28, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pager and AsyncPager raise IndexError when a list page is empty but next_page_token is set

2 participants