From 313c498073587c4cfeaa4c951ea00d448edb97ad Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Mon, 23 Nov 2026 23:09:10 -0500 Subject: [PATCH 1/4] OpenConceptLab/ocl_online#739 | The collection facets list only collection versions the requester can view A concept or mapping search's collection, collection_version and expansion facets named every collection version and expansion its matches belong to, as the index lists them: versions the requester can't view and versions since deleted too, with their member counts. For a requester who isn't staff, each name now counts only the matches in the versions they can view, by the rule the collection filter uses (Collection.get_viewable_versions_criteria), and a name with none is left out. A bucket's count is what its collection filter finds for them. The facet request also asks for the collection version URLs (and, outside global search, expansion URLs) among the matches, up to max_viewable_collection_urls; one query keeps the ones the requester can view. A name with one URL takes that URL's count; names with several get exact counts from one more size-0 request (a filters aggregation). Past the URL cap a name can undercount, but a version the requester can't view never shows. Staff are unchanged. A facetsOnly answer on a source version's list is cached for a day; its cache key now names the requester, so one requester's facets never reach another. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTpN4J5JFjNSmhYF49 --- core/common/mixins.py | 4 + core/common/search.py | 5 +- core/common/views.py | 83 ++++++++++++++++- .../integration_tests/tests_access_control.py | 92 ++++++++++++++++++- core/integration_tests/tests_concepts.py | 6 +- core/integration_tests/tests_mappings.py | 6 +- 6 files changed, 185 insertions(+), 11 deletions(-) diff --git a/core/common/mixins.py b/core/common/mixins.py index 041bb3bb7..cf5c715de 100644 --- a/core/common/mixins.py +++ b/core/common/mixins.py @@ -185,6 +185,10 @@ def __get_cached_data_if_any(self, request): if query_string: key_body += '?' + query_string key_headers += '?' + query_string + if self.only_facets(): # facets name only the collections the requester can view, so each gets their own + requester = f"#requester={get(request.user, 'id') if get(request.user, 'is_authenticated') else ''}" + key_body += requester + key_headers += requester return key_body, cache.get(key_body) or None, key_headers, cache.get(key_headers) or None diff --git a/core/common/search.py b/core/common/search.py index dc494e5c1..3abdf5ecb 100644 --- a/core/common/search.py +++ b/core/common/search.py @@ -39,8 +39,11 @@ def get_visible_repo_criteria(user): class CustomESFacetedSearch(FacetedSearch): - def __init__(self, query=None, filters=None, sort=(), _search=None): # pylint: disable=dangerous-default-value + def __init__(self, query=None, filters=None, sort=(), _search=None, extra_facets=None): # pylint: disable=dangerous-default-value + """extra_facets: facets to compute alongside the class's, by name.""" self._search = _search + if extra_facets: + self.facets = {**self.facets, **extra_facets} super().__init__(query=query, filters=filters or {}, sort=sort) @staticmethod diff --git a/core/common/views.py b/core/common/views.py index 214a10991..ef8da4fc7 100644 --- a/core/common/views.py +++ b/core/common/views.py @@ -13,7 +13,7 @@ from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from elasticsearch import RequestError, TransportError -from elasticsearch_dsl import Q +from elasticsearch_dsl import Q, TermsFacet from pydash import get, compact from rest_framework import response, generics, status from rest_framework.generics import ListAPIView, RetrieveUpdateDestroyAPIView @@ -27,7 +27,7 @@ LIMIT_PARAM, NOT_FOUND, MUST_SPECIFY_EXTRA_PARAM_IN_BODY, INCLUDE_RETIRED_PARAM, VERBOSE_PARAM, HEAD, LATEST, \ BRIEF_PARAM, ES_REQUEST_TIMEOUT, INCLUDE_INACTIVE, FHIR_LIMIT_PARAM, RAW_PARAM, SEARCH_MAP_CODES_PARAM, \ INCLUDE_SEARCH_META_PARAM, EXCLUDE_FUZZY_SEARCH_PARAM, EXCLUDE_WILDCARD_SEARCH_PARAM, UPDATED_BY_USERNAME_PARAM, \ - CANONICAL_URL_REQUEST_PARAM, CHECKSUMS_PARAM, ACCESS_TYPE_NONE, HTTP_COMPRESS_HEADER + CANONICAL_URL_REQUEST_PARAM, CHECKSUMS_PARAM, ACCESS_TYPE_NONE, HTTP_COMPRESS_HEADER, FACET_SIZE from core.common.exceptions import Http400 from core.common.mixins import PathWalkerMixin from core.common.permissions import CanViewConceptDictionary @@ -68,6 +68,9 @@ class BaseAPIView(generics.GenericAPIView, PathWalkerMixin): collection_facets = ('collection', 'collection_url', 'collection_owner_url') max_viewable_collection_urls = 1000 _viewable_collection_urls = None # get_viewable_collection_urls's, read once per request and facet value + # the facets that name collection versions or expansions, with the index field holding the URLs they come from + collection_url_facets = {'collection': 'collection_url', 'collection_version': 'collection_url', + 'expansion': 'expansion_url'} def get_throttles(self): return ThrottleUtil.get_throttles_by_user_plan(self.request.user) @@ -717,6 +720,8 @@ def exclude_hidden_latest_releases(self, results, latest_attr): def get_facets(self): # pylint: disable=too-many-branches facets = {} parent_repo = None + is_global_scope = ('org' not in self.kwargs and 'user' not in self.kwargs and not self.user_is_self) + url_facets = {} if self.facet_class: if self.is_user_document(): @@ -731,6 +736,9 @@ def get_facets(self): # pylint: disable=too-many-branches parent_repo = params['parent'] = get(self, 'parent_resource') if self.map_codes_release: params['release'] = self.map_codes_release + url_facets = self.get_collection_url_facets(is_global_scope) + if url_facets: + params['extra_facets'] = url_facets faceted_search = self.facet_class(**params) # pylint: disable=not-callable faceted_search.params(request_timeout=ES_REQUEST_TIMEOUT) @@ -743,7 +751,6 @@ def get_facets(self): # pylint: disable=too-many-branches facets.pop('updatedBy', None) if self.should_search_latest_repo() and self.is_source_child_document_model() and 'source_version' in facets: facets['source_version'] = [facet for facet in facets['source_version'] if facet[0] != 'HEAD'] - is_global_scope = ('org' not in self.kwargs and 'user' not in self.kwargs and not self.user_is_self) normalized_facet_concept_class = facets.pop('_conceptClass', None) or [] normalized_facet_datatype = facets.pop('_datatype', None) or [] @@ -767,12 +774,82 @@ def get_facets(self): # pylint: disable=too-many-branches facets.pop('collection_owner_url', None) facets.pop('is_in_latest_source_version', None) facets.pop('is_latest_version', None) + if url_facets: + self.keep_collection_facets_viewable(facets, url_facets, params['_search']) if parent_repo and self.is_concept_document(): return parent_repo.get_ordered_concept_facets_by_filter_order(facets) return facets + def get_collection_url_facets(self, is_global_scope): + """ + Facets listing the collection version URLs among a search's matches, and outside global search (where the + expansion facet is returned) their expansion URLs, with counts, for keep_collection_facets_viewable. None + ({}) for staff, who can view every version, or for a search of anything but concepts and mappings. + """ + from core.collections.models import Collection + if not self.is_source_child_document_model() or Collection.get_viewable_versions_criteria( + self.request.user) is None: + return {} + fields = ['collection_url'] if is_global_scope else ['collection_url', 'expansion_url'] + return {f'_{field}': TermsFacet(field=field, size=self.max_viewable_collection_urls) for field in fields} + + def keep_collection_facets_viewable(self, facets, url_facets, search): + """ + The collection, collection_version and expansion facets name the collection versions and expansions a match + is in as the index lists them: those the requester can't view, and those since deleted, too. Here each name + counts only the matches in the ones they can view, as the collection filter matches them + (get_collection_facet_criterion), and a name with none is left out. url_facets: get_collection_url_facets', + whose buckets, taken out of `facets`, give the URLs among the matches with their counts (the top + max_viewable_collection_urls: past them a name can undercount, never show). A name with one URL takes its + count; those with several are counted in one more request. + """ + url_counts = {name[1:]: {key: count for key, count, _ in facets.pop(name, [])} for name in url_facets} + names = self.get_viewable_collection_facet_urls( + [facet for facet in self.collection_url_facets if facets.get(facet)], url_counts) + counts, recounts = {}, {} + for (facet, name), urls in names.items(): + field = self.collection_url_facets[facet] + if len(urls) == 1: + counts[facet, name] = url_counts[field][urls[0]] + else: + recounts[facet, name] = Q('terms', **{field: urls}) + if recounts: + search = search.extra(size=0).params(request_timeout=ES_REQUEST_TIMEOUT) + search.aggs.bucket('viewable', 'filters', filters={str(i): query for i, query in enumerate( + recounts.values())}) + try: + buckets = search.execute().aggregations.viewable.buckets + except TransportError as ex: # pragma: no cover + raise Http400(detail=get(ex, 'info') or get(ex, 'error') or str(ex)) from ex + counts.update({key: buckets[str(i)].doc_count for i, key in enumerate(recounts)}) + for facet in self.collection_url_facets: + if facet in facets: + facets[facet] = sorted( + [(name, count, False) for (_facet, name), count in counts.items() if _facet == facet and count], + key=lambda bucket: (-bucket[1], bucket[0]))[:FACET_SIZE] + + def get_viewable_collection_facet_urls(self, facets, url_counts): + """ + {(facet, name): urls}: for each of these collection facets, the names it would show for the URLs in + url_counts of the collection versions (or expansions) the requester can view, each with those URLs. + """ + from core.collections.models import Collection, Expansion + viewable = Collection.objects.filter(Collection.get_viewable_versions_criteria(self.request.user)) + names = {} + if {'collection', 'collection_version'} & set(facets): + for uri, mnemonic, version in viewable.filter( + uri__in=url_counts.get('collection_url', [])).values_list('uri', 'mnemonic', 'version'): + names.setdefault(('collection', mnemonic), []).append(uri) + names.setdefault(('collection_version', version), []).append(uri) + if 'expansion' in facets: + for uri, mnemonic in Expansion.objects.filter( + uri__in=url_counts.get('expansion_url', []), collection_version__in=viewable).values_list( + 'uri', 'mnemonic'): + names.setdefault(('expansion', mnemonic), []).append(uri) + return {key: urls for key, urls in names.items() if key[0] in facets} + def get_extras_searchable_fields_from_query_params(self): query_params = self.request.query_params.dict() result = {} diff --git a/core/integration_tests/tests_access_control.py b/core/integration_tests/tests_access_control.py index a089b6110..6ae61545e 100644 --- a/core/integration_tests/tests_access_control.py +++ b/core/integration_tests/tests_access_control.py @@ -2108,7 +2108,8 @@ def setUp(self): super().setUp() self.patch_concept_es_mapping_for_ci() self.tag = f'qc{uuid.uuid4().hex[:6]}' - self.source = OrganizationSourceFactory(organization=self.org, public_access=ACCESS_TYPE_VIEW) + self.source = OrganizationSourceFactory( + organization=self.org, mnemonic=f'src{self.tag}', public_access=ACCESS_TYPE_VIEW) nowhere = ConceptFactory(parent=self.source, mnemonic=f'nowhere{self.tag}') self.concepts, self.mappings = {}, {} for key in ['inP', 'inQhead', 'inQv1', 'inRv1']: @@ -2271,6 +2272,95 @@ def test_collection_facets_on_a_cached_source_version_list_answer_each_requester self.assertEqual(self.listed(url, self.member, 'concepts'), ['inP'], url) self.assertEqual(self.listed(url, self.outsider, 'concepts'), [], url) self.assertEqual(self.listed(url, None, 'concepts'), [], url) + # a cached facetsOnly answer is each requester's own + url = f'{release.uri}concepts/' + self.assertIn(f'{self.tag}P', self.collection_facet(url, self.member)) + self.assertIn(f'{self.tag}P', self.collection_facet(url, self.staff)) + self.assertNotIn(f'{self.tag}P', self.collection_facet(url, self.outsider)) + self.assertNotIn(f'{self.tag}P', self.collection_facet(url, None)) + self.assertIn(f'{self.tag}P', self.collection_facet(url, self.member)) + + def facets(self, url, user): + """The facets `url` answers (facetsOnly), each a {name: count}.""" + response = self.request('get', f'{url}{"&" if "?" in url else "?"}facetsOnly=true', user) + self.assertEqual(response.status_code, 200, (url, user)) + return {facet: {bucket[0]: bucket[1] for bucket in buckets} + for facet, buckets in response.data['facets']['fields'].items()} + + def collection_facet(self, url, user): + """The collection facet `url` answers, this test's collections only.""" + return {name: count for name, count in self.facets(url, user).get('collection', {}).items() + if name.startswith(self.tag)} + + def add_latest_versions_to_heads(self): + """P's and Q's HEADs hold their concepts' and mappings' latest versions too, which facets read.""" + for head, key in [(self.p_head, 'inP'), (self.q_head, 'inQhead')]: + head.expansion.concepts.add(self.concepts[key].get_latest_version()) + head.expansion.mappings.add(self.mappings[key].get_latest_version()) + ConceptDocument().update(Concept.objects.filter(parent=self.source), refresh=True) + MappingDocument().update(Mapping.objects.filter(parent=self.source), refresh=True) + + def assert_collection_facets( # pylint: disable=too-many-arguments + self, outsiders, members, resources=('concepts', 'mappings'), staff=None, lists=True): + """ + Signed out and an outsider see the collection facet of this test's source `outsiders`; a member `members`, and + staff `staff` (by default `members`). With `lists`, each name counts what its collection filter lists for them + (a list filtered by collection reads every version; facets, like the unfiltered list, the latest). + """ + for resource in resources: + url = f'/{resource}/?source={self.source.mnemonic}' + for user, expected in [(None, outsiders), (self.outsider, outsiders), (self.member, members), + (self.staff, staff or members)]: + facet = self.collection_facet(url, user) + self.assertEqual(facet, {f'{self.tag}{name}': count for name, count in expected.items()}, (url, user)) + for name, count in facet.items() if lists else []: + rows = self.listed(f'{url}&collection={name}', user, resource) + self.assertEqual(len(rows), count, (name, user, resource, rows)) + + def test_the_collection_facet_names_only_versions_the_requester_can_view(self): + # facets read latest versions: Q's v1 alone holds one, which only members can view + self.assert_collection_facets({'R': 1}, {'P': 1, 'Q': 1, 'R': 1}, lists=False) + self.add_latest_versions_to_heads() + self.assert_collection_facets({'Q': 1, 'R': 1}, {'P': 1, 'Q': 2, 'R': 1}) + # a private collection of the same name under another owner counts only for those who can view it + other = OrganizationFactory() + other_q = OrganizationCollectionFactory( + organization=other, mnemonic=self.q_head.mnemonic, public_access=ACCESS_TYPE_NONE) + ExpansionFactory(collection_version=other_q).concepts.add( + *[concept.get_latest_version() for concept in self.concepts.values()]) + ConceptDocument().update(Concept.objects.filter(parent=self.source), refresh=True) + self.assert_collection_facets( + {'Q': 1, 'R': 1}, {'P': 1, 'Q': 2, 'R': 1}, ['concepts'], staff={'P': 1, 'Q': 4, 'R': 1}) + + def test_the_collection_facet_leaves_out_deleted_versions(self): + """The index keeps a deleted version's members until they're indexed again; staff see the index as it is.""" + self.add_latest_versions_to_heads() + Collection.objects.filter(id__in=[self.p_v1.id, self.p_head.id]).delete() + for resource in ['concepts', 'mappings']: + url = f'/{resource}/?source={self.source.mnemonic}' + self.assertEqual(self.collection_facet(url, self.member), {f'{self.tag}Q': 2, f'{self.tag}R': 1}) + self.assertEqual(self.collection_facet(url, self.staff), + {f'{self.tag}P': 1, f'{self.tag}Q': 2, f'{self.tag}R': 1}) + + def test_collection_version_and_expansion_facets_name_only_versions_the_requester_can_view(self): + hidden = OrganizationCollectionFactory( + organization=self.org, mnemonic=f'{self.tag}S', version=f'hidden{self.tag}', released=True, + public_access=ACCESS_TYPE_NONE) + ExpansionFactory(collection_version=hidden, mnemonic=f'hidden{self.tag}').concepts.add( + *[concept.get_latest_version() for concept in self.concepts.values()]) + self.add_latest_versions_to_heads() + url = f'{self.source.uri}concepts/' + for user in [None, self.outsider]: + facets = self.facets(url, user) + self.assertEqual(self.collection_facet(url, user), {f'{self.tag}Q': 1, f'{self.tag}R': 1}, user) + self.assertNotIn(f'hidden{self.tag}', facets['collection_version'], user) + self.assertNotIn(f'hidden{self.tag}', facets['expansion'], user) + self.assertEqual(facets['collection_version']['v1'], 1, user) + for user in [self.member, self.staff]: + facets = self.facets(url, user) + self.assertEqual(facets['collection_version'][f'hidden{self.tag}'], 4, user) + self.assertEqual(facets['expansion'][f'hidden{self.tag}'], 4, user) + self.assertEqual(self.facets(url, self.member)['collection_version']['v1'], 3) def test_a_prefix_matching_too_many_versions_answers_400(self): url = f'/concepts/?collection={self.tag}*' diff --git a/core/integration_tests/tests_concepts.py b/core/integration_tests/tests_concepts.py index db60bc05b..02c6f6440 100644 --- a/core/integration_tests/tests_concepts.py +++ b/core/integration_tests/tests_concepts.py @@ -3432,7 +3432,7 @@ def test_repo_version_concepts_with_hierarchy_includes_are_not_cached(self): def test_repo_version_concepts_facets_are_cached(self): body_key, _ = self.source_v1.get_concepts_cache_keys() - facets_key = body_key + '?facetsOnly=true' + facets_key = body_key + '?facetsOnly=true#requester=' # each requester's own; signed out share one response = self.client.get(f'/orgs/{self.org}/sources/MySource/v1/concepts/?facetsOnly=true') @@ -3447,7 +3447,7 @@ def test_repo_version_concepts_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true#requester=', {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -3460,7 +3460,7 @@ def test_head_version_concepts_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true#requester=')) def test_repo_version_concepts_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_concepts_cache_keys() diff --git a/core/integration_tests/tests_mappings.py b/core/integration_tests/tests_mappings.py index 69a395bc7..9717ca15d 100644 --- a/core/integration_tests/tests_mappings.py +++ b/core/integration_tests/tests_mappings.py @@ -1090,7 +1090,7 @@ def test_repo_version_mappings_are_served_from_cache(self): def test_repo_version_mappings_facets_are_cached(self): body_key, _ = self.source_v1.get_mappings_cache_keys() - facets_key = body_key + '?facetsOnly=true' + facets_key = body_key + '?facetsOnly=true#requester=' # each requester's own; signed out share one response = self.client.get(f'/orgs/{self.org}/sources/MapCacheSource/v1/mappings/?facetsOnly=true') @@ -1105,7 +1105,7 @@ def test_repo_version_mappings_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true#requester=', {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1118,7 +1118,7 @@ def test_head_version_mappings_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true#requester=')) def test_repo_version_mappings_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_mappings_cache_keys() From ad283a2b189cc81de9a66d343a648757ad78ad7e Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Mon, 23 Nov 2026 23:23:27 -0500 Subject: [PATCH 2/4] OpenConceptLab/ocl_online#739 | Collection facets count the top collections matched, and a cached facets answer is filtered for each requester Review pass 1 on oclapi2#1044: - The facets no longer list the version URLs among the matches, which stopped at 1,000: on a broad search, versions the requester can't view could crowd out the ones they can. The search now lists the top 300 collection names matched (`_collection_names`), and one query reads the viewable versions' expansions of those collections. A filters aggregation counts each collection, version name and expansion over the URLs those expansions give their members' documents, so the names read as the index has them (a version name with a space stays encoded). - A facetsOnly answer on a source version's list is cached again as anyone who can run the search sees it, and each answer, cached or not, is then filtered for its requester (get_requester_facets). A collection made private, or a member who leaves, no longer leaves its name in a cached answer. The cache key is the shared one again, and the updatedBy facet is dropped for signed-out requesters on cached answers too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTpN4J5JFjNSmhYF49 --- core/common/mixins.py | 10 +- core/common/views.py | 129 +++++++++--------- .../integration_tests/tests_access_control.py | 13 ++ core/integration_tests/tests_concepts.py | 10 +- core/integration_tests/tests_mappings.py | 10 +- 5 files changed, 90 insertions(+), 82 deletions(-) diff --git a/core/common/mixins.py b/core/common/mixins.py index cf5c715de..4b49204af 100644 --- a/core/common/mixins.py +++ b/core/common/mixins.py @@ -185,10 +185,6 @@ def __get_cached_data_if_any(self, request): if query_string: key_body += '?' + query_string key_headers += '?' + query_string - if self.only_facets(): # facets name only the collections the requester can view, so each gets their own - requester = f"#requester={get(request.user, 'id') if get(request.user, 'is_authenticated') else ''}" - key_body += requester - key_headers += requester return key_body, cache.get(key_body) or None, key_headers, cache.get(key_headers) or None @@ -239,6 +235,8 @@ def _list(self, request): # pylint:disable=too-many-locals,too-many-branches,to cache_key_body, data, cache_key_headers, headers = self.__get_cached_data_if_any(request) if self.request.query_params.get('_force_cache_clear') in TRUTHY: data = None + if data and self.only_facets(): # cached as anyone sees them, so as this requester sees them + return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}}) if not data: search_string = query_params.get('type', None) @@ -249,12 +247,12 @@ def _list(self, request): # pylint:disable=too-many-locals,too-many-branches,to return self.get_csv(request) if self.only_facets(): - data = {'facets': {'fields': self.get_facets()}} + data = {'facets': {'fields': self.get_facets(for_requester=False)}} # the same for everyone if cache_key_body is not None: timeout = 60 * 60 * 24 # 1 day cache.set(cache_key_body, data, timeout=timeout) cache.set(cache_key_headers, headers, timeout=timeout) - return Response(data) + return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}}) if self.only_search_stats() and search_term: return Response( self.get_search_stats( diff --git a/core/common/views.py b/core/common/views.py index ef8da4fc7..68ed178a6 100644 --- a/core/common/views.py +++ b/core/common/views.py @@ -68,6 +68,7 @@ class BaseAPIView(generics.GenericAPIView, PathWalkerMixin): collection_facets = ('collection', 'collection_url', 'collection_owner_url') max_viewable_collection_urls = 1000 _viewable_collection_urls = None # get_viewable_collection_urls's, read once per request and facet value + max_collection_facet_names = 3 * FACET_SIZE # keep_collection_facets_viewable's # the facets that name collection versions or expansions, with the index field holding the URLs they come from collection_url_facets = {'collection': 'collection_url', 'collection_version': 'collection_url', 'expansion': 'expansion_url'} @@ -717,11 +718,14 @@ def exclude_hidden_latest_releases(self, results, latest_attr): criterion = criteria if criterion is None else criterion | criteria return results if criterion is None else results.exclude(criterion) - def get_facets(self): # pylint: disable=too-many-branches + def get_facets(self, for_requester=True): # pylint: disable=too-many-branches + """ + The search's facets. Without for_requester, before get_requester_facets: the same for everyone who can run + the search, so they can be cached. + """ facets = {} parent_repo = None - is_global_scope = ('org' not in self.kwargs and 'user' not in self.kwargs and not self.user_is_self) - url_facets = {} + params = {} if self.facet_class: if self.is_user_document(): @@ -729,16 +733,15 @@ def get_facets(self): # pylint: disable=too-many-branches params = { 'query': self.get_search_string(lower=False), - '_search': self.__get_search_results( - ignore_retired_filter=True, sort=False, highlight=False, force=True) + '_search': self.get_facets_search() } if 'source' in self.kwargs and self.is_concept_document(): parent_repo = params['parent'] = get(self, 'parent_resource') if self.map_codes_release: params['release'] = self.map_codes_release - url_facets = self.get_collection_url_facets(is_global_scope) - if url_facets: - params['extra_facets'] = url_facets + if self.is_source_child_document_model(): # see keep_collection_facets_viewable + params['extra_facets'] = { + '_collection_names': TermsFacet(field='collection', size=self.max_collection_facet_names)} faceted_search = self.facet_class(**params) # pylint: disable=not-callable faceted_search.params(request_timeout=ES_REQUEST_TIMEOUT) @@ -747,10 +750,9 @@ def get_facets(self): # pylint: disable=too-many-branches facets = s.facets.to_dict() except TransportError as ex: # pragma: no cover raise Http400(detail=get(ex, 'info') or get(ex, 'error') or str(ex)) from ex - if not get(self.request.user, 'is_authenticated'): - facets.pop('updatedBy', None) if self.should_search_latest_repo() and self.is_source_child_document_model() and 'source_version' in facets: facets['source_version'] = [facet for facet in facets['source_version'] if facet[0] != 'HEAD'] + is_global_scope = ('org' not in self.kwargs and 'user' not in self.kwargs and not self.user_is_self) normalized_facet_concept_class = facets.pop('_conceptClass', None) or [] normalized_facet_datatype = facets.pop('_datatype', None) or [] @@ -774,81 +776,72 @@ def get_facets(self): # pylint: disable=too-many-branches facets.pop('collection_owner_url', None) facets.pop('is_in_latest_source_version', None) facets.pop('is_latest_version', None) - if url_facets: - self.keep_collection_facets_viewable(facets, url_facets, params['_search']) if parent_repo and self.is_concept_document(): - return parent_repo.get_ordered_concept_facets_by_filter_order(facets) + facets = parent_repo.get_ordered_concept_facets_by_filter_order(facets) - return facets + return self.get_requester_facets(facets, get(params, '_search')) if for_requester else facets - def get_collection_url_facets(self, is_global_scope): - """ - Facets listing the collection version URLs among a search's matches, and outside global search (where the - expansion facet is returned) their expansion URLs, with counts, for keep_collection_facets_viewable. None - ({}) for staff, who can view every version, or for a search of anything but concepts and mappings. - """ - from core.collections.models import Collection - if not self.is_source_child_document_model() or Collection.get_viewable_versions_criteria( - self.request.user) is None: - return {} - fields = ['collection_url'] if is_global_scope else ['collection_url', 'expansion_url'] - return {f'_{field}': TermsFacet(field=field, size=self.max_viewable_collection_urls) for field in fields} + def get_facets_search(self): + return self.__get_search_results(ignore_retired_filter=True, sort=False, highlight=False, force=True) - def keep_collection_facets_viewable(self, facets, url_facets, search): + def get_requester_facets(self, facets, search=None): + """get_facets(for_requester=False)'s facets as this requester sees them; `search`: get_facets_search's.""" + if not get(self.request.user, 'is_authenticated'): + facets.pop('updatedBy', None) + self.keep_collection_facets_viewable(facets, search) + return facets + + def keep_collection_facets_viewable(self, facets, search=None): """ The collection, collection_version and expansion facets name the collection versions and expansions a match is in as the index lists them: those the requester can't view, and those since deleted, too. Here each name counts only the matches in the ones they can view, as the collection filter matches them - (get_collection_facet_criterion), and a name with none is left out. url_facets: get_collection_url_facets', - whose buckets, taken out of `facets`, give the URLs among the matches with their counts (the top - max_viewable_collection_urls: past them a name can undercount, never show). A name with one URL takes its - count; those with several are counted in one more request. + (get_collection_facet_criterion), in one more request; a name with none is left out. Staff see them as they + are. The collections counted are those _collection_names lists: the top max_collection_facet_names among the + matches. One past them isn't counted, so its names can be missing, never wrong. """ - url_counts = {name[1:]: {key: count for key, count, _ in facets.pop(name, [])} for name in url_facets} - names = self.get_viewable_collection_facet_urls( - [facet for facet in self.collection_url_facets if facets.get(facet)], url_counts) - counts, recounts = {}, {} - for (facet, name), urls in names.items(): - field = self.collection_url_facets[facet] - if len(urls) == 1: - counts[facet, name] = url_counts[field][urls[0]] - else: - recounts[facet, name] = Q('terms', **{field: urls}) - if recounts: - search = search.extra(size=0).params(request_timeout=ES_REQUEST_TIMEOUT) - search.aggs.bucket('viewable', 'filters', filters={str(i): query for i, query in enumerate( - recounts.values())}) + from core.collections.models import Collection + collections = [name for name, _, _ in facets.pop('_collection_names', [])] + present = [facet for facet in self.collection_url_facets if facets.get(facet)] + viewable = Collection.get_viewable_versions_criteria(self.request.user) + if not present or viewable is None: + return + urls = self.get_viewable_collection_facet_urls(present, collections, viewable) + counts = {} + if urls: + search = (search or self.get_facets_search()).extra(size=0).params(request_timeout=ES_REQUEST_TIMEOUT) + search.aggs.bucket('viewable', 'filters', filters={ + str(i): Q('terms', **{self.collection_url_facets[facet]: sorted(values)}) + for i, ((facet, _), values) in enumerate(urls.items())}) try: buckets = search.execute().aggregations.viewable.buckets except TransportError as ex: # pragma: no cover raise Http400(detail=get(ex, 'info') or get(ex, 'error') or str(ex)) from ex - counts.update({key: buckets[str(i)].doc_count for i, key in enumerate(recounts)}) - for facet in self.collection_url_facets: - if facet in facets: - facets[facet] = sorted( - [(name, count, False) for (_facet, name), count in counts.items() if _facet == facet and count], - key=lambda bucket: (-bucket[1], bucket[0]))[:FACET_SIZE] - - def get_viewable_collection_facet_urls(self, facets, url_counts): + counts = {key: buckets[str(i)].doc_count for i, key in enumerate(urls)} + for facet in present: + facets[facet] = sorted( + [(name, count, False) for (_facet, name), count in counts.items() if _facet == facet and count], + key=lambda bucket: (-bucket[1], bucket[0]))[:FACET_SIZE] + + @staticmethod + def get_viewable_collection_facet_urls(facets, collections, viewable): """ - {(facet, name): urls}: for each of these collection facets, the names it would show for the URLs in - url_counts of the collection versions (or expansions) the requester can view, each with those URLs. + {(facet, name): urls} for these collection facets: each name they'd show for the expansions of these + collections' versions the requester can view (`viewable`), with its URLs (collection version URLs, or for + the expansion facet expansion URLs), read from each expansion as its members' documents read it. """ from core.collections.models import Collection, Expansion - viewable = Collection.objects.filter(Collection.get_viewable_versions_criteria(self.request.user)) - names = {} - if {'collection', 'collection_version'} & set(facets): - for uri, mnemonic, version in viewable.filter( - uri__in=url_counts.get('collection_url', [])).values_list('uri', 'mnemonic', 'version'): - names.setdefault(('collection', mnemonic), []).append(uri) - names.setdefault(('collection_version', version), []).append(uri) - if 'expansion' in facets: - for uri, mnemonic in Expansion.objects.filter( - uri__in=url_counts.get('expansion_url', []), collection_version__in=viewable).values_list( - 'uri', 'mnemonic'): - names.setdefault(('expansion', mnemonic), []).append(uri) - return {key: urls for key, urls in names.items() if key[0] in facets} + urls = {} + for expansion in Expansion.objects.filter(collection_version__in=Collection.objects.filter( + viewable, mnemonic__in=collections)).only('uri', 'mnemonic'): + for facet, name, url in [ + ('collection', expansion.collection_version_mnemonic, expansion.collection_version_url), + ('collection_version', expansion.collection_version_name, expansion.collection_version_url), + ('expansion', expansion.mnemonic, expansion.uri)]: + if facet in facets: + urls.setdefault((facet, name), set()).add(url) + return urls def get_extras_searchable_fields_from_query_params(self): query_params = self.request.query_params.dict() diff --git a/core/integration_tests/tests_access_control.py b/core/integration_tests/tests_access_control.py index 6ae61545e..b3a0867e9 100644 --- a/core/integration_tests/tests_access_control.py +++ b/core/integration_tests/tests_access_control.py @@ -2279,6 +2279,9 @@ def test_collection_facets_on_a_cached_source_version_list_answer_each_requester self.assertNotIn(f'{self.tag}P', self.collection_facet(url, self.outsider)) self.assertNotIn(f'{self.tag}P', self.collection_facet(url, None)) self.assertIn(f'{self.tag}P', self.collection_facet(url, self.member)) + # nor does it outlast the requester's access + self.member.organizations.remove(self.org) + self.assertNotIn(f'{self.tag}P', self.collection_facet(url, self.member)) def facets(self, url, user): """The facets `url` answers (facetsOnly), each a {name: count}.""" @@ -2349,7 +2352,17 @@ def test_collection_version_and_expansion_facets_name_only_versions_the_requeste ExpansionFactory(collection_version=hidden, mnemonic=f'hidden{self.tag}').concepts.add( *[concept.get_latest_version() for concept in self.concepts.values()]) self.add_latest_versions_to_heads() + spaced = OrganizationCollectionFactory( + organization=self.org, mnemonic=self.r_head.mnemonic, version='v 2', released=True, + public_access=ACCESS_TYPE_VIEW) + ExpansionFactory(collection_version=spaced).concepts.add(self.concepts['inRv1'].get_latest_version()) + ConceptDocument().update(Concept.objects.filter(parent=self.source), refresh=True) url = f'{self.source.uri}concepts/' + # a version's name reads as its members' documents have it, for everyone + spaced_keys = {key for key in self.facets(url, self.staff)['collection_version'] if key.startswith('v')} + self.assertEqual(len(spaced_keys), 2, spaced_keys) + for user in [None, self.outsider, self.member]: + self.assertLessEqual(spaced_keys, set(self.facets(url, user)['collection_version']), user) for user in [None, self.outsider]: facets = self.facets(url, user) self.assertEqual(self.collection_facet(url, user), {f'{self.tag}Q': 1, f'{self.tag}R': 1}, user) diff --git a/core/integration_tests/tests_concepts.py b/core/integration_tests/tests_concepts.py index 02c6f6440..635325e0d 100644 --- a/core/integration_tests/tests_concepts.py +++ b/core/integration_tests/tests_concepts.py @@ -3432,13 +3432,15 @@ def test_repo_version_concepts_with_hierarchy_includes_are_not_cached(self): def test_repo_version_concepts_facets_are_cached(self): body_key, _ = self.source_v1.get_concepts_cache_keys() - facets_key = body_key + '?facetsOnly=true#requester=' # each requester's own; signed out share one + facets_key = body_key + '?facetsOnly=true' response = self.client.get(f'/orgs/{self.org}/sources/MySource/v1/concepts/?facetsOnly=true') self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertEqual(cache.get(facets_key), response.data) + # cached as anyone sees them; answered as this requester (signed out: no updatedBy) sees them + cached = cache.get(facets_key)['facets']['fields'] + self.assertLessEqual(response.data['facets']['fields'].items(), cached.items()) self.assertIsNone(cache.get(body_key)) # facets do not collide with the plain listing def test_repo_version_concepts_facets_are_served_from_cache(self): @@ -3447,7 +3449,7 @@ def test_repo_version_concepts_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true#requester=', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -3460,7 +3462,7 @@ def test_head_version_concepts_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true#requester=')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) def test_repo_version_concepts_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_concepts_cache_keys() diff --git a/core/integration_tests/tests_mappings.py b/core/integration_tests/tests_mappings.py index 9717ca15d..f8fb80223 100644 --- a/core/integration_tests/tests_mappings.py +++ b/core/integration_tests/tests_mappings.py @@ -1090,13 +1090,15 @@ def test_repo_version_mappings_are_served_from_cache(self): def test_repo_version_mappings_facets_are_cached(self): body_key, _ = self.source_v1.get_mappings_cache_keys() - facets_key = body_key + '?facetsOnly=true#requester=' # each requester's own; signed out share one + facets_key = body_key + '?facetsOnly=true' response = self.client.get(f'/orgs/{self.org}/sources/MapCacheSource/v1/mappings/?facetsOnly=true') self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertEqual(cache.get(facets_key), response.data) + # cached as anyone sees them; answered as this requester (signed out: no updatedBy) sees them + cached = cache.get(facets_key)['facets']['fields'] + self.assertLessEqual(response.data['facets']['fields'].items(), cached.items()) self.assertIsNone(cache.get(body_key)) # facets do not collide with the plain listing def test_repo_version_mappings_facets_are_served_from_cache(self): @@ -1105,7 +1107,7 @@ def test_repo_version_mappings_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true#requester=', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1118,7 +1120,7 @@ def test_head_version_mappings_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true#requester=')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) def test_repo_version_mappings_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_mappings_cache_keys() From 029059205f6d5ddd77d0b5e367b5da38331d6c37 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Mon, 23 Nov 2026 23:46:24 -0500 Subject: [PATCH 3/4] OpenConceptLab/ocl_online#739 | Facets count collections as the collection filter matches them; shared facet entries get their own cache key Review pass 2 on oclapi2#1044: - The collection and collection_version facets count over the URLs of the collection versions the requester can view, as the collection filter matches them, rather than over their expansions. A version whose only expansion was deleted is still counted while its members' documents still name it. The expansion facet counts over expansion URLs. A version or expansion name is counted only if its facet lists it, so the count request stays the size of the facets. - A facetsOnly entry is cached as anyone sees it, under a key ending in `#for-anyone` (FACETS_CACHE_SUFFIX). So an answer cached before as one requester's, under the old key, is never read as anyone's, and code from before this change never reads the new entries. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTpN4J5JFjNSmhYF49 --- core/common/mixins.py | 4 +++ core/common/views.py | 29 +++++++++++-------- .../integration_tests/tests_access_control.py | 7 ++++- core/integration_tests/tests_concepts.py | 17 +++++++++-- core/integration_tests/tests_mappings.py | 7 +++-- 5 files changed, 45 insertions(+), 19 deletions(-) diff --git a/core/common/mixins.py b/core/common/mixins.py index 4b49204af..6c9b85f0c 100644 --- a/core/common/mixins.py +++ b/core/common/mixins.py @@ -46,6 +46,7 @@ INCLUDE_PARENT_CONCEPTS, INCLUDE_CHILD_CONCEPTS, INCLUDE_PARENT_CONCEPT_URLS, INCLUDE_CHILD_CONCEPT_URLS, INCLUDE_HIERARCHY_PATH, INCLUDE_SUMMARY) MAX_UNPAGINATED_RESULTS = 1000 # `Compress` lists; above this, users.list_unpaginated (ocl_online#230) +FACETS_CACHE_SUFFIX = '#for-anyone' # a facetsOnly answer's cache key ends with it class CustomPaginator: @@ -185,6 +186,9 @@ def __get_cached_data_if_any(self, request): if query_string: key_body += '?' + query_string key_headers += '?' + query_string + if self.only_facets(): # get_facets(for_requester=False)'s, not the answers cached before as one requester's + key_body += FACETS_CACHE_SUFFIX + key_headers += FACETS_CACHE_SUFFIX return key_body, cache.get(key_body) or None, key_headers, cache.get(key_headers) or None diff --git a/core/common/views.py b/core/common/views.py index 68ed178a6..9a5ed6ac0 100644 --- a/core/common/views.py +++ b/core/common/views.py @@ -803,7 +803,8 @@ def keep_collection_facets_viewable(self, facets, search=None): """ from core.collections.models import Collection collections = [name for name, _, _ in facets.pop('_collection_names', [])] - present = [facet for facet in self.collection_url_facets if facets.get(facet)] + present = {facet: {name for name, _, _ in facets[facet]} for facet in self.collection_url_facets + if facets.get(facet)} viewable = Collection.get_viewable_versions_criteria(self.request.user) if not present or viewable is None: return @@ -827,20 +828,24 @@ def keep_collection_facets_viewable(self, facets, search=None): @staticmethod def get_viewable_collection_facet_urls(facets, collections, viewable): """ - {(facet, name): urls} for these collection facets: each name they'd show for the expansions of these - collections' versions the requester can view (`viewable`), with its URLs (collection version URLs, or for - the expansion facet expansion URLs), read from each expansion as its members' documents read it. + {(facet, name): urls} for these collection facets ({facet: the names it lists}), from these collections' + versions the requester can view (`viewable`): their URLs by collection and version name, as the collection + filter matches them, and their expansions' URLs by expansion name. A version or expansion name counts only if + its facet lists it, so the request stays the facets' size. Names read as the documents read them from their + expansions' URIs (to_parent_kwargs_from_uri). """ from core.collections.models import Collection, Expansion + versions = Collection.objects.filter(viewable, mnemonic__in=collections) urls = {} - for expansion in Expansion.objects.filter(collection_version__in=Collection.objects.filter( - viewable, mnemonic__in=collections)).only('uri', 'mnemonic'): - for facet, name, url in [ - ('collection', expansion.collection_version_mnemonic, expansion.collection_version_url), - ('collection_version', expansion.collection_version_name, expansion.collection_version_url), - ('expansion', expansion.mnemonic, expansion.uri)]: - if facet in facets: - urls.setdefault((facet, name), set()).add(url) + for uri in versions.values_list('uri', flat=True): + parts = uri.strip('/').split('/') + for facet, name in [('collection', parts[3]), ('collection_version', parts[4] if len(parts) > 4 else HEAD)]: + if facet in facets and (facet == 'collection' or name in facets[facet]): + urls.setdefault((facet, name), set()).add(uri) + if 'expansion' in facets: + for uri, name in Expansion.objects.filter( + collection_version__in=versions, mnemonic__in=facets['expansion']).values_list('uri', 'mnemonic'): + urls.setdefault(('expansion', name), set()).add(uri) return urls def get_extras_searchable_fields_from_query_params(self): diff --git a/core/integration_tests/tests_access_control.py b/core/integration_tests/tests_access_control.py index b3a0867e9..e319308d2 100644 --- a/core/integration_tests/tests_access_control.py +++ b/core/integration_tests/tests_access_control.py @@ -11,7 +11,7 @@ from django.test import tag, override_settings from core.client_configs.models import ClientConfig from core.collections.documents import CollectionDocument -from core.collections.models import Collection, CollectionReference +from core.collections.models import Collection, CollectionReference, Expansion from core.collections.tests.factories import OrganizationCollectionFactory, UserCollectionFactory, ExpansionFactory from core.common.constants import ACCESS_TYPE_NONE, ACCESS_TYPE_VIEW, RETIRED_ACCESS_TYPE_EDIT, ROLE_ADMIN from core.common.permissions import HasOwnership @@ -2344,6 +2344,11 @@ def test_the_collection_facet_leaves_out_deleted_versions(self): self.assertEqual(self.collection_facet(url, self.member), {f'{self.tag}Q': 2, f'{self.tag}R': 1}) self.assertEqual(self.collection_facet(url, self.staff), {f'{self.tag}P': 1, f'{self.tag}Q': 2, f'{self.tag}R': 1}) + # an expansion deleted alone leaves its version's indexed members counted, as the collection filter finds them + Expansion.objects.filter(collection_version=self.r_v1).delete() + url = f'/concepts/?source={self.source.mnemonic}' + self.assertEqual(self.collection_facet(url, None), {f'{self.tag}Q': 1, f'{self.tag}R': 1}) + self.assertEqual(self.listed(f'{url}&collection={self.tag}R', None, 'concepts'), ['inRv1']) def test_collection_version_and_expansion_facets_name_only_versions_the_requester_can_view(self): hidden = OrganizationCollectionFactory( diff --git a/core/integration_tests/tests_concepts.py b/core/integration_tests/tests_concepts.py index 635325e0d..e15232dda 100644 --- a/core/integration_tests/tests_concepts.py +++ b/core/integration_tests/tests_concepts.py @@ -26,6 +26,7 @@ from core.sources.models import CloneLimitExceeded from core.collections.tests.factories import OrganizationCollectionFactory, ExpansionFactory from core.common.constants import ACCESS_TYPE_NONE, OPENMRS_VALIDATION_SCHEMA +from core.common.mixins import FACETS_CACHE_SUFFIX from core.common.tests import OCLAPITestCase, PREVIEW_GROUP_NAME from core.concepts.constants import CONCEPT_HARD_DELETE_REQUIRES_HEAD_ONLY from core.concepts.documents import ConceptDocument @@ -3432,7 +3433,7 @@ def test_repo_version_concepts_with_hierarchy_includes_are_not_cached(self): def test_repo_version_concepts_facets_are_cached(self): body_key, _ = self.source_v1.get_concepts_cache_keys() - facets_key = body_key + '?facetsOnly=true' + facets_key = body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX response = self.client.get(f'/orgs/{self.org}/sources/MySource/v1/concepts/?facetsOnly=true') @@ -3449,12 +3450,22 @@ def test_repo_version_concepts_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX, {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, {'facets': {'fields': {'fromCache': []}}}) + def test_repo_version_concepts_facets_ignore_answers_cached_before(self): + """An answer cached for one requester before facets were cached for anyone isn't read for another.""" + body_key, _ = self.source_v1.get_concepts_cache_keys() + cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + + response = self.client.get(f'/orgs/{self.org}/sources/MySource/v1/concepts/?facetsOnly=true') + + self.assertEqual(response.status_code, 200) + self.assertNotIn('fromCache', response.data['facets']['fields']) + def test_head_version_concepts_facets_are_not_cached(self): body_key, _ = self.source.get_concepts_cache_keys() @@ -3462,7 +3473,7 @@ def test_head_version_concepts_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX)) def test_repo_version_concepts_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_concepts_cache_keys() diff --git a/core/integration_tests/tests_mappings.py b/core/integration_tests/tests_mappings.py index f8fb80223..da4975158 100644 --- a/core/integration_tests/tests_mappings.py +++ b/core/integration_tests/tests_mappings.py @@ -4,6 +4,7 @@ from rest_framework.exceptions import ErrorDetail from core.collections.tests.factories import OrganizationCollectionFactory, ExpansionFactory +from core.common.mixins import FACETS_CACHE_SUFFIX from core.common.tests import OCLAPITestCase from core.concepts.tests.factories import ConceptFactory, ConceptNameFactory from core.integration_tests.test_utils import SourceChildListQueryCountMixin @@ -1090,7 +1091,7 @@ def test_repo_version_mappings_are_served_from_cache(self): def test_repo_version_mappings_facets_are_cached(self): body_key, _ = self.source_v1.get_mappings_cache_keys() - facets_key = body_key + '?facetsOnly=true' + facets_key = body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX response = self.client.get(f'/orgs/{self.org}/sources/MapCacheSource/v1/mappings/?facetsOnly=true') @@ -1107,7 +1108,7 @@ def test_repo_version_mappings_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX, {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1120,7 +1121,7 @@ def test_head_version_mappings_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX)) def test_repo_version_mappings_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_mappings_cache_keys() From b73149ae0965b3b144bdc4acb7d5091502eb49d8 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Mon, 23 Nov 2026 23:58:45 -0500 Subject: [PATCH 4/4] OpenConceptLab/ocl_online#739 | Test: the collection_version and expansion facets aren't query-string filters Naming one of their buckets in the query string lists the scope as it is (review on oclapi2#1044). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTpN4J5JFjNSmhYF49 --- core/integration_tests/tests_access_control.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/integration_tests/tests_access_control.py b/core/integration_tests/tests_access_control.py index e319308d2..e0c81a48a 100644 --- a/core/integration_tests/tests_access_control.py +++ b/core/integration_tests/tests_access_control.py @@ -2379,6 +2379,10 @@ def test_collection_version_and_expansion_facets_name_only_versions_the_requeste self.assertEqual(facets['collection_version'][f'hidden{self.tag}'], 4, user) self.assertEqual(facets['expansion'][f'hidden{self.tag}'], 4, user) self.assertEqual(self.facets(url, self.member)['collection_version']['v1'], 3) + # neither facet is a query-string filter: naming one of their buckets lists the scope as it is + everything = self.listed(url, self.outsider, 'concepts') + for query in ['collectionVersion=v1', f'collectionVersion=hidden{self.tag}', f'expansion=hidden{self.tag}']: + self.assertEqual(self.listed(f'{url}?{query}', self.outsider, 'concepts'), everything, query) def test_a_prefix_matching_too_many_versions_answers_400(self): url = f'/concepts/?collection={self.tag}*'