From 85e036dcc8fa23304aafe405d7bf25c4dc5084dc Mon Sep 17 00:00:00 2001 From: "ran.liao" Date: Thu, 3 Sep 2026 13:35:30 +0900 Subject: [PATCH 1/6] Only request the total count when it is needed LazyGraphQuery added meta.totalCount to the selection of every graph list query so that len() could answer without fetching. On the server that field is a count over the whole matching set, so every caller paid for a scan it had usually not asked for, and a caller that deliberately left meta out had no way to avoid it. Two changes remove it. A query whose limit already fits in one page has nothing to paginate, so it now skips the lazy wrapper and runs as a single plain query with the fields the caller chose. An unbounded query still goes through LazyGraphQuery, but the count is fetched on demand by len(), indexing and totalCount rather than up front, so a caller that only iterates never pays for one. Paging itself never needed the count, GraphQueryIterator stops when a page comes back short. Fetching the whole result to measure it instead was considered and rejected. That would defeat the point of the class on exactly the large tables it exists to protect. Callers that select meta keep the previous behaviour. The v1 LazyQuery behind GetScenes is untouched, it takes its total from the REST meta. --- CHANGELOG.md | 10 +++ .../test_webstackclient.py | 52 +++++++++++++++ python/mujinwebstackclient/version.py | 2 +- .../webstackgraphclientutils.py | 65 +++++++++++++++++-- 4 files changed, 124 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5db65bd..2d42e57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.1.2 (2026-09-01) + +- Graph list queries no longer ask the server for `meta.totalCount` unless the caller selected + it. `LazyGraphQuery` used to add the field to every request so that `len()` could answer + without fetching, which made each call pay for a count of the whole matching set. Automatic + paging never needed it, `GraphQueryIterator` stops on a short page, so the count is now + requested only when it was asked for. `len()`, `repr()` and indexing fall back to fetching the + result when it is absent, so they still return the same answers. Callers that select + `meta` are unaffected, as is the v1 `LazyQuery` used by `GetScenes` and friends. + ## 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..f5d0e31 100644 --- a/python/mujintestwebstackclient/test_webstackclient.py +++ b/python/mujintestwebstackclient/test_webstackclient.py @@ -347,6 +347,58 @@ 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 actually needs it + """ + 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 answered by a single plain query, with no count + with requests_mock.Mocker() as mock: + _RegisterMockListEnvironmentsAPI(mock, totalCount) + + queryResult = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}}, options={'first': 1}) + assert [environment['id'] for environment in queryResult['environments']] == ['0'] + assert 'meta' not in queryResult + assert len(mock.request_history) == 1 + 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 + + # an unbounded query pays for no count until something needs one + with requests_mock.Mocker() as mock: + _RegisterMockListEnvironmentsAPI(mock, totalCount) + + environments = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}})['environments'] + assert _CountTotalCountQueries(mock) == 0 + + # len() asks for the count on its own rather than fetching every page to measure it + assert len(environments) == totalCount + assert _CountTotalCountQueries(mock) == 1 + assert len(mock.request_history) == 2, 'len() walked the pages instead of querying the count' + assert list.__len__(environments) == 0, 'len() materialized the result instead of counting it' + + # iterating never needs a count, it stops on a short page + with requests_mock.Mocker() as mock: + _RegisterMockListEnvironmentsAPI(mock, totalCount) + + environments = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}})['environments'] + assert [environment['id'] for environment in environments] == [str(index) for index in range(totalCount)] + assert _CountTotalCountQueries(mock) == 0 + + 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..8b1cb27 100644 --- a/python/mujinwebstackclient/webstackgraphclientutils.py +++ b/python/mujinwebstackclient/webstackgraphclientutils.py @@ -274,14 +274,17 @@ 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. Paging does not + # need it, GraphQueryIterator stops on a short page, so it is read by len(), + # repr() and indexing alone and those fall back to fetching without it. The + # count is a scan of the whole matching set on the server, so a caller that + # did not ask for it must not be charged for it. + if 'meta' in self._currentFields and type(self._currentFields['meta']) is 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 + # establish the key name and type name with a minimal webstack call self._currentOffset = self._initialOffset self._currentLimit = 1 self._APICall() @@ -298,6 +301,42 @@ def __iter__(self): self._queryKwargs['options']['first'] = self._initialLimit return GraphQueryIterator(self._queryFunction, *self._queryArgs, **self._queryKwargs) + def _EnsureTotalCount(self): + """Query the total count on its own, for the members that cannot answer without one. + + Fetching the whole result to measure it would defeat the point of this class, so the + count is asked for directly instead. It stays cheap for a caller that never needs it. + """ + if self._totalCount is not None: + return + queryKwargs = copy.deepcopy(self._queryKwargs) + queryKwargs['fields'] = {'meta': {'totalCount': None}} + 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) + self._totalCount = data['meta']['totalCount'] + + # The three members below need a total to answer. It is absent when the caller did not + # select meta, so they fetch just the count at that point rather than the whole result. + + 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 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 + 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 +374,12 @@ def typeName(self): """ return self._typeName + @property + def totalCount(self): + """the number of items available in webstack, queried 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: @@ -354,6 +399,18 @@ def UseLazyGraphQuery(queryFunction): def wrapper(self, *args, **kwargs): if 'fields' in kwargs and not isinstance(kwargs['fields'], dict): kwargs['fields'] = {key: None for key in kwargs['fields']} + + # A limit that already fits in one page has nothing to paginate, so answer it with a + # single plain query. Going through LazyGraphQuery would add a round trip and, for a + # caller that selected meta, a count over the whole matching set. + first = (kwargs.get('options') or {}).get('first') or 0 + if 0 < first <= webstackclientutils.GetMaximumQueryLimit(0): + # copy before defaulting the offset, so the caller's own dictionaries are left alone + kwargs = dict(kwargs) + kwargs['options'] = dict(kwargs['options']) + kwargs['options'].setdefault('offset', 0) + return queryFunction(self, *args, **kwargs) + queryResult = LazyGraphQuery(queryFunction, *((self,) + args), **kwargs) response = {} if queryResult.typeName is not None: From ee9ac7b0fd9a1ef57915a4154c24b4500883ac1b Mon Sep 17 00:00:00 2001 From: "ran.liao" Date: Thu, 3 Sep 2026 13:35:30 +0900 Subject: [PATCH 2/6] Changelog, version --- CHANGELOG.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d42e57..a9a783a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,13 +2,13 @@ ## 1.1.2 (2026-09-01) -- Graph list queries no longer ask the server for `meta.totalCount` unless the caller selected - it. `LazyGraphQuery` used to add the field to every request so that `len()` could answer - without fetching, which made each call pay for a count of the whole matching set. Automatic - paging never needed it, `GraphQueryIterator` stops on a short page, so the count is now - requested only when it was asked for. `len()`, `repr()` and indexing fall back to fetching the - result when it is absent, so they still return the same answers. Callers that select - `meta` are unaffected, as is the v1 `LazyQuery` used by `GetScenes` and friends. +- Graph list queries no longer ask webstack for `meta.totalCount` unless it is needed. + `LazyGraphQuery` used to add the field to every request so that `len()` could answer without + fetching, which charged every caller for a count over the whole matching set. A query whose + limit already fits in a single page now skips the lazy wrapper and runs as one plain query, + and an unbounded query asks for the count only when `len()`, indexing or `totalCount` + actually needs one. Paging itself never needed it, `GraphQueryIterator` stops on a short + page. Callers that select `meta` are unaffected, as is the v1 `LazyQuery` behind `GetScenes`. ## 1.1.1 (2026-09-01) From b902c078dbeabd2d266d5525973e28ca79521edd Mon Sep 17 00:00:00 2001 From: "ran.liao" Date: Fri, 4 Sep 2026 09:47:08 +0900 Subject: [PATCH 3/6] Always return LazyGraphQuery, keep the single page from the first call Review feedback: skipping the wrapper for a single page changed the payload from LazyGraphQuery to a plain list, so callers lost FetchAll(), totalCount and the other helpers. That made the API harder to use for a saving that can be had without it. UseLazyGraphQuery is back to what it was. Instead, the call the constructor already makes to learn the key name and type name now fetches the whole window when the requested limit fits in one page, and keeps it. The result is complete at that point, so len(), indexing and repr() answer from the items and still need no count, while the return type is unchanged. repr() on such a query is now the real list rather than the elided partial form, since the items are known to be the whole result. --- CHANGELOG.md | 11 +++++---- .../test_webstackclient.py | 9 ++++++-- .../webstackgraphclientutils.py | 23 ++++++++----------- 3 files changed, 22 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9a783a..da686fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,12 @@ - Graph list queries no longer ask webstack for `meta.totalCount` unless it is needed. `LazyGraphQuery` used to add the field to every request so that `len()` could answer without - fetching, which charged every caller for a count over the whole matching set. A query whose - limit already fits in a single page now skips the lazy wrapper and runs as one plain query, - and an unbounded query asks for the count only when `len()`, indexing or `totalCount` - actually needs one. Paging itself never needed it, `GraphQueryIterator` stops on a short - page. Callers that select `meta` are unaffected, as is the v1 `LazyQuery` behind `GetScenes`. + fetching, which charged every caller for a count over the whole matching set. A limit that + already fits in a single page is now satisfied by the first call and kept, so it needs no count + at all, and an unbounded query asks for one only when `len()`, indexing or `totalCount` needs + it. Paging itself never needed the count, `GraphQueryIterator` stops on a short page. The + return type is unchanged, callers still get a `LazyGraphQuery`. Callers that select `meta` are + unaffected, as is the v1 `LazyQuery` behind `GetScenes`. ## 1.1.1 (2026-09-01) diff --git a/python/mujintestwebstackclient/test_webstackclient.py b/python/mujintestwebstackclient/test_webstackclient.py index f5d0e31..c4e65c0 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): @@ -364,10 +364,15 @@ def test_LazyGraphQueryOnlyRequestsTotalCountWhenSelected(): _RegisterMockListEnvironmentsAPI(mock, totalCount) queryResult = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}}, options={'first': 1}) - assert [environment['id'] for environment in queryResult['environments']] == ['0'] + 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 stays a LazyGraphQuery so callers keep the list-like helpers + assert isinstance(environments, LazyGraphQuery) + environments.FetchAll() + assert _CountTotalCountQueries(mock) == 0 # selecting meta on that same query still returns the count with requests_mock.Mocker() as mock: diff --git a/python/mujinwebstackclient/webstackgraphclientutils.py b/python/mujinwebstackclient/webstackgraphclientutils.py index 8b1cb27..50c6d33 100644 --- a/python/mujinwebstackclient/webstackgraphclientutils.py +++ b/python/mujinwebstackclient/webstackgraphclientutils.py @@ -284,10 +284,17 @@ def __init__(self, queryFunction, *args, **kwargs): # e.g. client.graphApi.ListEnvironments(fields={'meta': None}) self._currentFields['meta'].setdefault('totalCount', None) - # establish the key name and type name with a minimal webstack call + # Establish the key name and type name with one webstack call. A limit that already fits + # in a single page is satisfied by that very call, so fetch the whole window at once and + # keep it. len(), indexing and repr() then answer from the items, and the most common + # bounded query needs no count at all. self._currentOffset = self._initialOffset - self._currentLimit = 1 + fitsInOnePage = 0 < self._initialLimit <= webstackclientutils.GetMaximumQueryLimit(0) + self._currentLimit = self._initialLimit if fitsInOnePage else 1 self._APICall() + if fitsInOnePage: + list.__init__(self, self._items) + self._fetchedAll = True # update the current limit self._currentLimit = webstackclientutils.GetMaximumQueryLimit(self._initialLimit) @@ -399,18 +406,6 @@ def UseLazyGraphQuery(queryFunction): def wrapper(self, *args, **kwargs): if 'fields' in kwargs and not isinstance(kwargs['fields'], dict): kwargs['fields'] = {key: None for key in kwargs['fields']} - - # A limit that already fits in one page has nothing to paginate, so answer it with a - # single plain query. Going through LazyGraphQuery would add a round trip and, for a - # caller that selected meta, a count over the whole matching set. - first = (kwargs.get('options') or {}).get('first') or 0 - if 0 < first <= webstackclientutils.GetMaximumQueryLimit(0): - # copy before defaulting the offset, so the caller's own dictionaries are left alone - kwargs = dict(kwargs) - kwargs['options'] = dict(kwargs['options']) - kwargs['options'].setdefault('offset', 0) - return queryFunction(self, *args, **kwargs) - queryResult = LazyGraphQuery(queryFunction, *((self,) + args), **kwargs) response = {} if queryResult.typeName is not None: From 365ad4bf81eb820ce4c5f00892ae572b9561bc51 Mon Sep 17 00:00:00 2001 From: "ran.liao" Date: Fri, 4 Sep 2026 12:08:52 +0900 Subject: [PATCH 4/6] Limit the change to queries that fit in a single page Removing the up-front count from every lazy graph query was too broad. An unbounded query returns a LazyGraphQuery whose len() and truthiness need a total, and deferring that to an on-demand query changed the behaviour of callers that iterate such a result. The sensor link migration reads ListBodies that way, and with the total missing it stopped finding the attached sensors, which left sensorbridges.conf with an empty sensor list and broke the simulator test suite downstream. Narrow it to the case that is provably free. A limit that already fits in one page is satisfied by the call the constructor already makes, so fetch the whole window there and keep it. That query is complete, needs no total, and asks for no count. Every other query asks for the count up front exactly as before, so nothing that pages changes at all. This also removes the on-demand count and the len(), indexing and repr() overrides that existed only to cope with a missing total. --- CHANGELOG.md | 15 ++-- .../test_webstackclient.py | 28 +++---- .../webstackgraphclientutils.py | 73 ++++--------------- 3 files changed, 33 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da686fa..533a966 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,13 @@ ## 1.1.2 (2026-09-01) -- Graph list queries no longer ask webstack for `meta.totalCount` unless it is needed. - `LazyGraphQuery` used to add the field to every request so that `len()` could answer without - fetching, which charged every caller for a count over the whole matching set. A limit that - already fits in a single page is now satisfied by the first call and kept, so it needs no count - at all, and an unbounded query asks for one only when `len()`, indexing or `totalCount` needs - it. Paging itself never needed the count, `GraphQueryIterator` stops on a short page. The - return type is unchanged, callers still get a `LazyGraphQuery`. Callers that select `meta` are - unaffected, as is the v1 `LazyQuery` behind `GetScenes`. +- A graph list query whose limit already fits in a single page no longer makes webstack count the + whole matching set. `LazyGraphQuery` added `meta.totalCount` to every request so that `len()` + could answer without fetching, but such a query is complete after the first call, so `len()`, + indexing and `repr()` can answer from the items and no count is needed. Queries that page are + unchanged and still ask for the total up front. The return type is unchanged, callers still get + a `LazyGraphQuery` with `FetchAll()`, `totalCount` and the other list helpers. The v1 + `LazyQuery` behind `GetScenes` is untouched. ## 1.1.1 (2026-09-01) diff --git a/python/mujintestwebstackclient/test_webstackclient.py b/python/mujintestwebstackclient/test_webstackclient.py index c4e65c0..3dce3c9 100644 --- a/python/mujintestwebstackclient/test_webstackclient.py +++ b/python/mujintestwebstackclient/test_webstackclient.py @@ -353,13 +353,13 @@ def _CountTotalCountQueries(mocker): 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 actually needs it + """a limit that fits one page is complete after the first call, so it needs no total and + must not make the server count the whole matching set. every other query is unchanged. """ 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 answered by a single plain query, with no count + # a limit that fits one page: one request, no count, and still a LazyGraphQuery with requests_mock.Mocker() as mock: _RegisterMockListEnvironmentsAPI(mock, totalCount) @@ -369,8 +369,9 @@ def test_LazyGraphQueryOnlyRequestsTotalCountWhenSelected(): assert 'meta' not in queryResult assert len(mock.request_history) == 1 assert _CountTotalCountQueries(mock) == 0 - # the payload stays a LazyGraphQuery so callers keep the list-like helpers + # the payload keeps the list-like helpers, and the window is already complete assert isinstance(environments, LazyGraphQuery) + assert len(environments) == 1 environments.FetchAll() assert _CountTotalCountQueries(mock) == 0 @@ -382,26 +383,17 @@ def test_LazyGraphQueryOnlyRequestsTotalCountWhenSelected(): assert queryResult['meta'] == {'totalCount': totalCount} assert _CountTotalCountQueries(mock) == 1 - # an unbounded query pays for no count until something needs one + # a query that needs paging is untouched, it still asks for the total up front so that + # len() and indexing answer without another round trip with requests_mock.Mocker() as mock: _RegisterMockListEnvironmentsAPI(mock, totalCount) environments = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}})['environments'] - assert _CountTotalCountQueries(mock) == 0 - - # len() asks for the count on its own rather than fetching every page to measure it - assert len(environments) == totalCount assert _CountTotalCountQueries(mock) == 1 - assert len(mock.request_history) == 2, 'len() walked the pages instead of querying the count' - assert list.__len__(environments) == 0, 'len() materialized the result instead of counting it' - - # iterating never needs a count, it stops on a short page - with requests_mock.Mocker() as mock: - _RegisterMockListEnvironmentsAPI(mock, totalCount) - - environments = webstackclient.graphApi.ListEnvironments(fields={'environments': {'id': None}})['environments'] + requestsSoFar = len(mock.request_history) + assert len(environments) == totalCount + assert len(mock.request_history) == requestsSoFar, 'len() should not have queried again' assert [environment['id'] for environment in environments] == [str(index) for index in range(totalCount)] - assert _CountTotalCountQueries(mock) == 0 def test_LazyQueryStandardListOperations(): diff --git a/python/mujinwebstackclient/webstackgraphclientutils.py b/python/mujinwebstackclient/webstackgraphclientutils.py index 50c6d33..f3c1c84 100644 --- a/python/mujinwebstackclient/webstackgraphclientutils.py +++ b/python/mujinwebstackclient/webstackgraphclientutils.py @@ -274,22 +274,23 @@ def __init__(self, queryFunction, *args, **kwargs): else: self._currentFields = self._queryKwargs['fields'] - # Only ask for the total count when the caller selected meta. Paging does not - # need it, GraphQueryIterator stops on a short page, so it is read by len(), - # repr() and indexing alone and those fall back to fetching without it. The - # count is a scan of the whole matching set on the server, so a caller that - # did not ask for it must not be charged for it. - if 'meta' in self._currentFields and type(self._currentFields['meta']) is 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) - - # Establish the key name and type name with one webstack call. A limit that already fits - # in a single page is satisfied by that very call, so fetch the whole window at once and - # keep it. len(), indexing and repr() then answer from the items, and the most common - # bounded query needs no count at all. - self._currentOffset = self._initialOffset + # A limit that already fits in a single page is satisfied by the one call below, so the + # window is complete and len(), indexing and repr() answer from the items. Such a query + # needs no total at all, and asking for one costs a count over the whole matching set on + # the server. Every other query still asks for the count up front, unchanged, because + # callers depend on the total being there without another round trip. fitsInOnePage = 0 < self._initialLimit <= webstackclientutils.GetMaximumQueryLimit(0) + if not fitsInOnePage: + # initialize meta and total count + self._currentFields.setdefault('meta', {}) + if type(self._currentFields['meta']) is 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) + + # fetch the whole window when it fits one page, otherwise just enough to establish the + # key name, the type name and the total count + self._currentOffset = self._initialOffset self._currentLimit = self._initialLimit if fitsInOnePage else 1 self._APICall() if fitsInOnePage: @@ -308,42 +309,6 @@ def __iter__(self): self._queryKwargs['options']['first'] = self._initialLimit return GraphQueryIterator(self._queryFunction, *self._queryArgs, **self._queryKwargs) - def _EnsureTotalCount(self): - """Query the total count on its own, for the members that cannot answer without one. - - Fetching the whole result to measure it would defeat the point of this class, so the - count is asked for directly instead. It stays cheap for a caller that never needs it. - """ - if self._totalCount is not None: - return - queryKwargs = copy.deepcopy(self._queryKwargs) - queryKwargs['fields'] = {'meta': {'totalCount': None}} - 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) - self._totalCount = data['meta']['totalCount'] - - # The three members below need a total to answer. It is absent when the caller did not - # select meta, so they fetch just the count at that point rather than the whole result. - - 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 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 - 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 @@ -381,12 +346,6 @@ def typeName(self): """ return self._typeName - @property - def totalCount(self): - """the number of items available in webstack, queried 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: From e55944506823da5ce29396648a4f005a9f904702 Mon Sep 17 00:00:00 2001 From: "ran.liao" Date: Fri, 4 Sep 2026 13:19:14 +0900 Subject: [PATCH 5/6] Fetch the total count on demand, and stop needing it so often Limiting the saving to single page queries left the common case paying for a count nobody asked for. Fetch it on demand instead, and remove the reasons a caller ends up needing it. Truthiness now answers from the page fetched in the constructor rather than falling through to len(), so the "result or []" shape costs nothing. There are fifteen of those in migration and sensorbridges alone. An index that falls inside that page is returned from it for the same reason, which covers the "result[0]" shape. Paging already needed no total, GraphQueryIterator stops when a page comes back short. When a total really is required, the query keeps the caller's field selection and adds meta to it. That matters: a resolver such as ListBodies gates loading the rows on the data field being selected, so a query asking for meta alone counts an empty slice and reports zero. Asking for meta on its own is what previously made an unbounded result look empty and broke the sensor link migration. --- CHANGELOG.md | 18 ++-- .../test_webstackclient.py | 42 +++++++-- .../webstackgraphclientutils.py | 85 +++++++++++++++---- 3 files changed, 113 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 533a966..8db9e91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,13 +2,17 @@ ## 1.1.2 (2026-09-01) -- A graph list query whose limit already fits in a single page no longer makes webstack count the - whole matching set. `LazyGraphQuery` added `meta.totalCount` to every request so that `len()` - could answer without fetching, but such a query is complete after the first call, so `len()`, - indexing and `repr()` can answer from the items and no count is needed. Queries that page are - unchanged and still ask for the total up front. The return type is unchanged, callers still get - a `LazyGraphQuery` with `FetchAll()`, `totalCount` and the other list helpers. The v1 - `LazyQuery` behind `GetScenes` is untouched. +- Graph list queries no longer make webstack count the whole matching set unless the count is + actually needed. `LazyGraphQuery` used to add `meta.totalCount` to every request so that + `len()` could answer without fetching. It is now fetched on demand, and several things that + used to force it no longer do: a limit that fits one page is complete after the first call, + truthiness is answered by that page rather than falling through to `len()`, and an index + inside it is returned from it. Paging never needed the total, `GraphQueryIterator` stops on a + short page. When a total is genuinely required the query keeps the caller's field selection, + since a resolver such as `ListBodies` only loads, and so only counts, the rows when the data + field is selected. The return type is unchanged, callers still get a `LazyGraphQuery` with + `FetchAll()`, `totalCount` and the other list helpers. The v1 `LazyQuery` behind `GetScenes` + is untouched. ## 1.1.1 (2026-09-01) diff --git a/python/mujintestwebstackclient/test_webstackclient.py b/python/mujintestwebstackclient/test_webstackclient.py index 3dce3c9..0862b04 100644 --- a/python/mujintestwebstackclient/test_webstackclient.py +++ b/python/mujintestwebstackclient/test_webstackclient.py @@ -353,13 +353,13 @@ def _CountTotalCountQueries(mocker): def test_LazyGraphQueryOnlyRequestsTotalCountWhenSelected(): - """a limit that fits one page is complete after the first call, so it needs no total and - must not make the server count the whole matching set. every other query is unchanged. + """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: one request, no count, and still a LazyGraphQuery + # 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) @@ -369,7 +369,7 @@ def test_LazyGraphQueryOnlyRequestsTotalCountWhenSelected(): assert 'meta' not in queryResult assert len(mock.request_history) == 1 assert _CountTotalCountQueries(mock) == 0 - # the payload keeps the list-like helpers, and the window is already complete + # the payload keeps the list-like helpers assert isinstance(environments, LazyGraphQuery) assert len(environments) == 1 environments.FetchAll() @@ -383,17 +383,41 @@ def test_LazyGraphQueryOnlyRequestsTotalCountWhenSelected(): assert queryResult['meta'] == {'totalCount': totalCount} assert _CountTotalCountQueries(mock) == 1 - # a query that needs paging is untouched, it still asks for the total up front so that - # len() and indexing answer without another round trip + # 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 - requestsSoFar = len(mock.request_history) + + # 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 - assert len(mock.request_history) == requestsSoFar, 'len() should not have queried again' - assert [environment['id'] for environment in environments] == [str(index) for index in range(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(): diff --git a/python/mujinwebstackclient/webstackgraphclientutils.py b/python/mujinwebstackclient/webstackgraphclientutils.py index f3c1c84..4bb9872 100644 --- a/python/mujinwebstackclient/webstackgraphclientutils.py +++ b/python/mujinwebstackclient/webstackgraphclientutils.py @@ -274,27 +274,23 @@ def __init__(self, queryFunction, *args, **kwargs): else: self._currentFields = self._queryKwargs['fields'] - # A limit that already fits in a single page is satisfied by the one call below, so the - # window is complete and len(), indexing and repr() answer from the items. Such a query - # needs no total at all, and asking for one costs a count over the whole matching set on - # the server. Every other query still asks for the count up front, unchanged, because - # callers depend on the total being there without another round trip. + # 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 'meta' in self._currentFields and type(self._currentFields['meta']) is 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) + + # 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) - if not fitsInOnePage: - # initialize meta and total count - self._currentFields.setdefault('meta', {}) - if type(self._currentFields['meta']) is 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) - - # fetch the whole window when it fits one page, otherwise just enough to establish the - # key name, the type name and the total count self._currentOffset = self._initialOffset self._currentLimit = self._initialLimit if fitsInOnePage else 1 self._APICall() if fitsInOnePage: - list.__init__(self, self._items) + list.__init__(self, self._items or []) self._fetchedAll = True # update the current limit @@ -309,6 +305,57 @@ 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 + return '[..., ' + (self._items or []).__repr__()[1:-1] + ', ...]' + return super(LazyGraphQuery, self).__repr__() + def _APICall(self): """Make one webstack query""" # fetch data starting from the requested offset and limit @@ -346,6 +393,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: From 5436dca22c2e6ff2506febac5c1d02ff70993beb Mon Sep 17 00:00:00 2001 From: Barkin Simsek Date: Mon, 7 Sep 2026 10:27:57 +0900 Subject: [PATCH 6/6] fix: handle empty page in LazyGraphQuery repr, tighten changelog --- CHANGELOG.md | 15 ++++----------- .../webstackgraphclientutils.py | 6 ++++-- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8db9e91..3f81935 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,17 +2,10 @@ ## 1.1.2 (2026-09-01) -- Graph list queries no longer make webstack count the whole matching set unless the count is - actually needed. `LazyGraphQuery` used to add `meta.totalCount` to every request so that - `len()` could answer without fetching. It is now fetched on demand, and several things that - used to force it no longer do: a limit that fits one page is complete after the first call, - truthiness is answered by that page rather than falling through to `len()`, and an index - inside it is returned from it. Paging never needed the total, `GraphQueryIterator` stops on a - short page. When a total is genuinely required the query keeps the caller's field selection, - since a resolver such as `ListBodies` only loads, and so only counts, the rows when the data - field is selected. The return type is unchanged, callers still get a `LazyGraphQuery` with - `FetchAll()`, `totalCount` and the other list helpers. The v1 `LazyQuery` behind `GetScenes` - is untouched. +- `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) diff --git a/python/mujinwebstackclient/webstackgraphclientutils.py b/python/mujinwebstackclient/webstackgraphclientutils.py index 4bb9872..3a3727e 100644 --- a/python/mujinwebstackclient/webstackgraphclientutils.py +++ b/python/mujinwebstackclient/webstackgraphclientutils.py @@ -278,7 +278,7 @@ def __init__(self, queryFunction, *args, **kwargs): # 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 'meta' in self._currentFields and type(self._currentFields['meta']) is dict: + 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) @@ -353,7 +353,9 @@ 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 - return '[..., ' + (self._items or []).__repr__()[1:-1] + ', ...]' + if not self._items: + return '[...]' + return '[..., ' + self._items.__repr__()[1:-1] + ', ...]' return super(LazyGraphQuery, self).__repr__() def _APICall(self):