jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/439643 )
Change subject: Fix handling of API continuation in PropertyGenerator ......................................................................
Fix handling of API continuation in PropertyGenerator
test_preload_langlinks_count was marked as allowed_failure. It relies on site.preloadpages, which relies on PropertyGenerator, which had a bug in it.
The issue was that the default implementation of QueryGenerator returns incomplete results: Sometimes the API splits long pageprops into several API requests. But QueryGenerator returns the result as soon it gets it, without waiting for it to complete in the next request. In other words, PropertyGenerator used to yield more than expected, but each yield had less than expected fields. Therefore site.preloadpages returned more pages than expected, but the preloaded data on each page could be incomplete. There are many other function that rely on PropertyGenerator and might be effected by the bug, but I have not performed any test to confirm that.
I don't know if other generators also have a similar bug or not. This patch only tries to fix PropertyGenerator. If such issues are found in other generators as well, then it might make sense to move some of the newly introduced PropertyGenerator methods into QueryGenerator.
api.py: - QueryGenerator: Do a refactoring to move a small part of `__iter__` into a separate function (_extract_results). We can override and extend this function later in the PropertyGenerator subclass. - PropertyGenerator: Override `__iter__` and `_extract_results` in a way to prevent yielding premature results. A result is considered fully fetched if it is not found in the next request results.
site_tests.py: - Remove the allowed_failure decorator and reenable the test. - Silence the output.
Bug: T196876 Change-Id: I4ed74ab3af6d320242beaef1a55f20dc489fe29b --- M pywikibot/data/api.py M tests/site_tests.py 2 files changed, 83 insertions(+), 36 deletions(-)
Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py index 4e677cb..de17ab5 100644 --- a/pywikibot/data/api.py +++ b/pywikibot/data/api.py @@ -2750,7 +2750,7 @@ value = str(value) self.request[key] = value
- def _handle_query_limit(self, prev_limit, new_limit, count, had_data): + def _handle_query_limit(self, prev_limit, new_limit, had_data): """Handle query limit.""" if self.query_limit is None: return prev_limit, new_limit @@ -2761,7 +2761,7 @@ elif self.limit > 0: if had_data: # self.resultkey in data in last request.submit() - new_limit = min(self.query_limit, self.limit - count) + new_limit = min(self.query_limit, self.limit - self._count) else: # only "(query-)continue" returned. See Bug T74209. # increase new_limit to advance faster until new @@ -2791,7 +2791,7 @@ api=self.api_limit, limit=self.limit, new=new_limit, - count=count, + count=self._count, prefix=self.prefix, value=self.request[self.prefix + 'limit']), _logger) @@ -2818,6 +2818,30 @@ _logger) return resultdata
+ def _extract_results(self, resultdata): + """Extract results from resultdata.""" + for item in resultdata: + result = self.result(item) + if self._namespaces: + if not self._check_result_namespace(result): + continue + yield result + if isinstance(item, dict) \ + and set(self.continuekey) & set(item.keys()): + # if we need to count elements contained in items in + # self.data["query"]["pages"], we want to count + # item[self.continuekey] (e.g. 'revisions') and not + # self.resultkey (i.e. 'pages') + for key in set(self.continuekey) & set(item.keys()): + self._count += len(item[key]) + # otherwise we proceed as usual + else: + self._count += 1 + # note: self.limit could be -1 + if self.limit and 0 < self.limit <= self._count: + raise RuntimeError( + 'QueryGenerator._extract_results reached the limit') + def __iter__(self): """Submit request and iterate the response based on self.resultkey.
@@ -2827,10 +2851,10 @@ previous_result_had_data = True prev_limit = new_limit = None
- count = 0 + self._count = 0 while True: prev_limit, new_limit = self._handle_query_limit( - prev_limit, new_limit, count, previous_result_had_data) + prev_limit, new_limit, previous_result_had_data) if not hasattr(self, "data"): self.data = self.request.submit() if not self.data or not isinstance(self.data, dict): @@ -2847,26 +2871,11 @@ for item in self.data['query']['normalized']} else: self.normalized = {} - for item in resultdata: - result = self.result(item) - if self._namespaces: - if not self._check_result_namespace(result): - continue - yield result - if isinstance(item, dict) \ - and set(self.continuekey) & set(item.keys()): - # if we need to count elements contained in items in - # self.data["query"]["pages"], we want to count - # item[self.continuekey] (e.g. 'revisions') and not - # self.resultkey (i.e. 'pages') - for key in set(self.continuekey) & set(item.keys()): - count += len(item[key]) - # otherwise we proceed as usual - else: - count += 1 - # note: self.limit could be -1 - if self.limit and self.limit > 0 and count >= self.limit: - return + try: + for result in self._extract_results(resultdata): + yield result + except RuntimeError: + return # self.resultkey in data in last request.submit() previous_result_had_data = True else: @@ -3020,6 +3029,46 @@ """The requested property names.""" return self._props
+ def __iter__(self): + """Yield results.""" + self._previous_dicts = {} + for result in super(PropertyGenerator, self).__iter__(): + yield result + for result in self._previous_dicts.values(): + yield result + + def _extract_results(self, resultdata): + """Yield completed page_data of consecutive API requests.""" + for d in self._fully_retrieved_data_dicts(resultdata): + yield d + for data_dict in super(PropertyGenerator, self)._extract_results( + resultdata + ): + d = self._previous_dicts.setdefault(data_dict['title'], data_dict) + if d is not data_dict: + self._update_old_result_dict(d, data_dict) + + def _fully_retrieved_data_dicts(self, resultdata): + """Yield items of self._previous_dicts that are not in resultdata.""" + resuldata_titles = {d['title'] for d in resultdata} + for prev_title, prev_dict in self._previous_dicts.copy().items(): + if prev_title not in resuldata_titles: + yield prev_dict + del self._previous_dicts[prev_title] + + @staticmethod + def _update_old_result_dict(old_dict, new_dict): + """Update old result dict with new_dict.""" + for k, v in new_dict.items(): + if k not in old_dict: + old_dict[k] = v + continue + if isinstance(v, list): + old_dict[k].extend(v) + continue + assert isinstance(v, (UnicodeType, int)), ( + 'continued API result had an unexpected type: %s' % type(v)) +
class ListGenerator(QueryGenerator):
diff --git a/tests/site_tests.py b/tests/site_tests.py index cfaa47e..64db605 100644 --- a/tests/site_tests.py +++ b/tests/site_tests.py @@ -31,7 +31,7 @@ UnicodeType as unicode, )
-from tests import unittest_print +from tests import patch, unittest_print from tests.aspects import ( unittest, TestCase, DeprecationTestCase, TestCaseBase, @@ -3060,16 +3060,14 @@ if count >= 6: break
- @allowed_failure - def test_preload_langlinks_count(self): + @patch.object(pywikibot, 'output') + def test_preload_langlinks_count(self, output_mock): """Test preloading continuation works.""" - # FIXME: test fails mysite = self.get_site() mainpage = self.get_mainpage() - count = 0 - links = mysite.pagelinks(mainpage, total=20) - pages = list(mysite.preloadpages(links, groupsize=5, - langlinks=True)) + links = list(mysite.pagelinks(mainpage, total=20)) + pages = list(mysite.preloadpages(links, groupsize=5, langlinks=True)) + self.assertEqual(len(links), len(pages)) for page in pages: self.assertIsInstance(page, pywikibot.Page) self.assertIsInstance(page.exists(), bool) @@ -3077,9 +3075,9 @@ self.assertEqual(len(page._revisions), 1) self.assertIsNotNone(page._revisions[page._revid].text) self.assertFalse(hasattr(page, '_pageprops')) - count += 1 - - self.assertEqual(len(list(links)), count) + if pages: + self.assertRegex( + output_mock.call_args[0][0], r'Retrieving \d pages from ')
def _test_preload_langlinks_long(self): """Test preloading continuation works."""
pywikibot-commits@lists.wikimedia.org