diff --git a/CHANGELOG.md b/CHANGELOG.md index 5db65bd..3f81935 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.1.2 (2026-09-01) + +- `LazyGraphQuery` no longer requests `meta.totalCount` on every graph list query. The count is + fetched on demand by `len()`, `totalCount` and out-of-page indexing. A limit that fits one page + is complete after the first call, truthiness and in-page indexing answer from the fetched page, + and iteration stops on a short page. Return type unchanged. The v1 `LazyQuery` is untouched. + ## 1.1.1 (2026-09-01) - Encode `multipart/form-data` request bodies directly when every field holds in-memory data diff --git a/python/mujintestwebstackclient/test_webstackclient.py b/python/mujintestwebstackclient/test_webstackclient.py index 64d1d27..0862b04 100644 --- a/python/mujintestwebstackclient/test_webstackclient.py +++ b/python/mujintestwebstackclient/test_webstackclient.py @@ -16,7 +16,7 @@ from mujinwebstackclient import controllerwebclientraw from mujinwebstackclient.webstackclient import WebstackClient from mujinwebstackclient.webstackclientutils import QueryIterator, GetMaximumQueryLimit -from mujinwebstackclient.webstackgraphclientutils import GraphQueryIterator +from mujinwebstackclient.webstackgraphclientutils import GraphQueryIterator, LazyGraphQuery def _RegisterMockGetScenesAPI(mocker, totalCount): @@ -347,6 +347,79 @@ def test_GraphQueryIteratorAndLazyGraphQuery(): } +def _CountTotalCountQueries(mocker): + """number of requests in the history that asked webstack for the total count""" + return sum('totalCount' in request.json()['query'] for request in mocker.request_history) + + +def test_LazyGraphQueryOnlyRequestsTotalCountWhenSelected(): + """the total count is a scan of the whole matching set on the server, so it is asked for only + when the caller selected meta or when something genuinely needs a length + """ + totalCount = 2500 # more than one page, so paging would show up in the request count + webstackclient = WebstackClient('http://controller', 'mujin', 'mujin') + + # a limit that fits one page is complete after the first call, so it needs no count + with requests_mock.Mocker() as mock: + _RegisterMockListEnvironmentsAPI(mock, totalCount) + + queryResult = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}}, options={'first': 1}) + environments = queryResult['environments'] + assert [environment['id'] for environment in environments] == ['0'] + assert 'meta' not in queryResult + assert len(mock.request_history) == 1 + assert _CountTotalCountQueries(mock) == 0 + # the payload keeps the list-like helpers + assert isinstance(environments, LazyGraphQuery) + assert len(environments) == 1 + environments.FetchAll() + assert _CountTotalCountQueries(mock) == 0 + + # selecting meta on that same query still returns the count + with requests_mock.Mocker() as mock: + _RegisterMockListEnvironmentsAPI(mock, totalCount) + + queryResult = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}, 'meta': {'totalCount': None}}, options={'first': 1}) + assert queryResult['meta'] == {'totalCount': totalCount} + assert _CountTotalCountQueries(mock) == 1 + + # a query that has to page costs no count until something needs a length + with requests_mock.Mocker() as mock: + _RegisterMockListEnvironmentsAPI(mock, totalCount) + + environments = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}})['environments'] + assert _CountTotalCountQueries(mock) == 0 + + # truthiness is answered by the page already fetched, this is the "result or []" shape + assert bool(environments) is True + assert _CountTotalCountQueries(mock) == 0 + + # an index inside that page is answered from it too + assert environments[0]['id'] == '0' + assert _CountTotalCountQueries(mock) == 0 + + # iterating stops on a short page and never needs a total + assert [environment['id'] for environment in environments] == [str(index) for index in range(totalCount)] + assert _CountTotalCountQueries(mock) == 0 + + # only a real length asks for one + assert len(environments) == totalCount + assert _CountTotalCountQueries(mock) == 1 + + # the count query must keep the caller's field selection. a resolver such as ListBodies only + # loads, and so only counts, the rows when the data field is selected, and a meta-only query + # would report zero and make the result look empty + with requests_mock.Mocker() as mock: + _RegisterMockListEnvironmentsAPI(mock, totalCount) + + environments = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}})['environments'] + assert len(environments) == totalCount + countingRequests = [request for request in mock.request_history if 'totalCount' in request.json()['query']] + assert countingRequests, 'expected a request to fetch the count' + for request in countingRequests: + assert 'environments' in request.json()['query'], 'the count was requested without the data selection' + + def test_LazyQueryStandardListOperations(): """test standard list operations""" totalCount = 1000 diff --git a/python/mujinwebstackclient/version.py b/python/mujinwebstackclient/version.py index 44829ba..8e31c60 100644 --- a/python/mujinwebstackclient/version.py +++ b/python/mujinwebstackclient/version.py @@ -1,3 +1,3 @@ -__version__ = '1.1.1' +__version__ = '1.1.2' # Do not forget to update CHANGELOG.md diff --git a/python/mujinwebstackclient/webstackgraphclientutils.py b/python/mujinwebstackclient/webstackgraphclientutils.py index e0b593f..3a3727e 100644 --- a/python/mujinwebstackclient/webstackgraphclientutils.py +++ b/python/mujinwebstackclient/webstackgraphclientutils.py @@ -274,17 +274,24 @@ def __init__(self, queryFunction, *args, **kwargs): else: self._currentFields = self._queryKwargs['fields'] - # initialize meta and total count - self._currentFields.setdefault('meta', {}) - if type(self._currentFields['meta']) is dict: + # Only ask for the total count when the caller selected meta. Nothing in paging needs it, + # GraphQueryIterator stops on a short page, and truthiness answers from the first page, + # so len(), indexing and totalCount fetch it on demand instead. The count is a scan of + # the whole matching set on the server, so a caller that never needs it must not pay. + if isinstance(self._currentFields.get('meta'), dict): # do not modify fields if caller provided incorrect meta fields # e.g. client.graphApi.ListEnvironments(fields={'meta': None}) self._currentFields['meta'].setdefault('totalCount', None) - # get the meta only with a minimal webstack call + # fetch the whole window when the limit fits one page, in which case the result is + # already complete, otherwise just enough to establish the key name and the type name + fitsInOnePage = 0 < self._initialLimit <= webstackclientutils.GetMaximumQueryLimit(0) self._currentOffset = self._initialOffset - self._currentLimit = 1 + self._currentLimit = self._initialLimit if fitsInOnePage else 1 self._APICall() + if fitsInOnePage: + list.__init__(self, self._items or []) + self._fetchedAll = True # update the current limit self._currentLimit = webstackclientutils.GetMaximumQueryLimit(self._initialLimit) @@ -298,6 +305,59 @@ def __iter__(self): self._queryKwargs['options']['first'] = self._initialLimit return GraphQueryIterator(self._queryFunction, *self._queryArgs, **self._queryKwargs) + def _EnsureTotalCount(self): + """Fetch the total count on demand, keeping the caller's own field selection. + + The selection has to be kept. A resolver such as ListBodies only loads, and therefore + only counts, the rows when the data field is selected, so a query asking for meta alone + would report zero. Fetching one row alongside the count is the price of a correct total. + """ + if self._totalCount is not None: + return + queryKwargs = copy.deepcopy(self._queryKwargs) + fields = dict(self._currentFields) + fields['meta'] = {'totalCount': None} + queryKwargs['fields'] = fields + queryKwargs['options']['offset'] = self._initialOffset + # a limit of zero means unlimited to webstack, and some queries reject it outright + queryKwargs['options']['first'] = 1 + data = self._queryFunction(*self._queryArgs, **queryKwargs) + if 'meta' in data: + self._totalCount = data['meta']['totalCount'] + + def __bool__(self): + # Truthiness only asks whether there is at least one item, which the page already + # fetched answers. Falling through to __len__ would make "result or []" pay for a count. + if self._fetchedAll: + return list.__len__(self) > 0 + if self._totalCount is not None: + return self._totalCount > self._initialOffset + return len(self._items or []) > 0 + + def __len__(self): + if not self._fetchedAll: + self._EnsureTotalCount() + return super(LazyGraphQuery, self).__len__() + + def __getitem__(self, index): + if not self._fetchedAll and type(index) is int and index >= 0: + # an index already inside the buffered page needs no total to bounds check against + offset = self._initialOffset + index + if self._currentOffset <= offset < self._currentOffset + len(self._items or []): + return (self._items or [])[offset - self._currentOffset] + if not self._fetchedAll and type(index) is not slice: + self._EnsureTotalCount() + return super(LazyGraphQuery, self).__getitem__(index) + + def __repr__(self): + if not self._fetchedAll and self._totalCount is None: + # repr must not reach the network, so without a total the buffer cannot be + # compared against the full result and is reported as partial + if not self._items: + return '[...]' + return '[..., ' + self._items.__repr__()[1:-1] + ', ...]' + return super(LazyGraphQuery, self).__repr__() + def _APICall(self): """Make one webstack query""" # fetch data starting from the requested offset and limit @@ -335,6 +395,12 @@ def typeName(self): """ return self._typeName + @property + def totalCount(self): + """the number of items available in webstack, fetched on demand when the caller did not select meta""" + self._EnsureTotalCount() + return self._totalCount + def FetchAll(self): """fetch the complete query result from webstack""" if self._fetchedAll: