Skip to content
22 changes: 22 additions & 0 deletions core/collections/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,28 @@ def expansion(self):

return None

@staticmethod
def annotate_expansion_health(queryset):
"""Each version's default expansion's health state and whether it's current, in the same query"""
# scoped to the version's own expansions, as Collection.expansion is
default_expansion = Expansion.objects.filter(
uri=models.OuterRef('expansion_uri'), collection_version_id=models.OuterRef('id'))
return queryset.annotate(
expansion_health_state=models.Subquery(default_expansion.values('health__state')[:1]),
expansion_health_is_current=models.Subquery(default_expansion.values('health_is_current')[:1]))

@staticmethod
def get_expansion_health(version):
"""{state, is_current} of the version's default expansion; None until it has been computed"""
if hasattr(version, 'expansion_health_state'):
state, is_current = version.expansion_health_state, version.expansion_health_is_current
elif version.expansion_uri:
state, is_current = version.expansions.filter(uri=version.expansion_uri).values_list(
'health__state', 'health_is_current').first() or (None, None)
else:
state, is_current = None, None
return {'state': state, 'is_current': is_current} if state else None

@cached_property
def locked_source_versions(self):
return self.get_locked_repo_versions('evaluated_source_versions')
Expand Down
30 changes: 26 additions & 4 deletions core/collections/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,15 +119,29 @@ class CollectionVersionListSerializer(ModelSerializer):
expansion_url = CharField(source='expansion_uri', read_only=True)
checksums = SerializerMethodField()
external_exports = SerializerMethodField()
expansion_health = SerializerMethodField()

class Meta:
model = Collection
fields = (
'type', 'short_code', 'name', 'url', 'canonical_url', 'owner', 'owner_type', 'owner_url', 'version',
'created_at', 'id', 'collection_type', 'updated_at', 'released', 'retired', 'version_url',
'previous_version_url', 'autoexpand', 'expansion_url', 'checksums', 'external_exports', 'verification'
'previous_version_url', 'autoexpand', 'expansion_url', 'checksums', 'external_exports', 'verification',
'expansion_health'
)

def to_representation(self, instance):
data = super().to_representation(instance)
if not hasattr(instance, 'expansion_health_state'):
# only the versions list annotates it, so version lists nested elsewhere add no query per row
data.pop('expansion_health', None)
return data

@staticmethod
def get_expansion_health(obj):
# only rows the versions list annotated: everywhere else the field is dropped, so no lookup per row
return Collection.get_expansion_health(obj) if hasattr(obj, 'expansion_health_state') else None

def __init__(self, *args, **kwargs):
params = get(kwargs, 'context.request.query_params')

Expand Down Expand Up @@ -510,6 +524,7 @@ class CollectionVersionDetailSerializer(CollectionCreateOrUpdateSerializer, Abst
states = SerializerMethodField()
tasks = SerializerMethodField()
external_exports = SerializerMethodField()
expansion_health = SerializerMethodField()

class Meta:
model = Collection
Expand All @@ -522,10 +537,15 @@ class Meta:
'version', 'concepts_url', 'mappings_url', 'expansions_url', 'is_processing', 'released', 'retired',
'canonical_url', 'identifier', 'publisher', 'contact', 'jurisdiction', 'purpose', 'copyright', 'meta',
'immutable', 'revision_date', 'summary', 'text', 'experimental', 'locked_date',
'autoexpand', 'expansion_url', 'checksums', 'states', 'tasks', 'external_exports', 'verification'
'autoexpand', 'expansion_url', 'checksums', 'states', 'tasks', 'external_exports', 'verification',
'expansion_health'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: this also reaches every collection version export. CollectionVersionExportSerializer exports all of this serializer's fields except VERSION_EXPORT_EXCLUDED_FIELDS ({'verification'}).

So exports now carry a health snapshot that goes stale on the next recompute, two exports of an unchanged version can differ by it alone, and each export runs one more query. Exclude it the way verification is excluded:

VERSION_EXPORT_EXCLUDED_FIELDS = {'verification', 'expansion_health'}

Also add a test that the export leaves it out.

) + AbstractRepoResourcesSerializer.Meta.fields
read_only_fields = ('verification',)

@staticmethod
def get_expansion_health(obj):
return Collection.get_expansion_health(obj)

def __init__(self, *args, **kwargs):
params = get(kwargs, 'context.request.query_params')
self.include_summary = False
Expand Down Expand Up @@ -665,8 +685,9 @@ class Meta:
model = Expansion
fields = (
'mnemonic', 'id', 'parameters', 'canonical_url', 'url', 'summary', 'is_processing',
'collection_version', 'extras'
'collection_version', 'extras', 'health', 'health_is_current'
)
read_only_fields = ('health', 'health_is_current')

def __init__(self, *args, **kwargs):
params = get(kwargs, 'context.request.query_params')
Expand Down Expand Up @@ -710,8 +731,9 @@ class Meta:
'mnemonic', 'id', 'parameters', 'canonical_url', 'url', 'summary', 'created_on', 'created_by',
'is_processing', 'unresolved_repo_versions', 'collection_version',
'explicit_collection_versions', 'explicit_source_versions',
'evaluated_collection_versions', 'evaluated_source_versions', 'extras'
'evaluated_collection_versions', 'evaluated_source_versions', 'extras', 'health', 'health_is_current'
)
read_only_fields = ('health', 'health_is_current')

def __init__(self, *args, **kwargs):
params = get(kwargs, 'context.request.query_params')
Expand Down
120 changes: 119 additions & 1 deletion core/collections/tests/tests_health.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from core.collections.tests.factories import OrganizationCollectionFactory, ExpansionFactory
from core.common.constants import ACCESS_TYPE_NONE, ACCESS_TYPE_VIEW
from core.common.tasks import seed_children_to_new_version, recheck_expansion_health
from core.common.tests import OCLTestCase
from core.common.tests import OCLTestCase, OCLAPITestCase
from core.concepts.tests.factories import ConceptFactory
from core.mappings.tests.factories import MappingFactory
from core.sources.models import Source
Expand Down Expand Up @@ -897,3 +897,121 @@ def test_version_created_from_head_stores_health(self, _):
version.refresh_from_db()
self.assertTrue(version.expansion.health_is_current)
self.assertIsNotNone(version.expansion.health['state'])


class ExpansionHealthAPITest(OCLAPITestCase):
def setUp(self):
super().setUp()
self.collection = OrganizationCollectionFactory()
self.expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='autoexpand-HEAD')
self.collection.expansion_uri = self.expansion.uri
self.collection.save()
self.concept = ConceptFactory()
self.collection.add_expressions({'expressions': [self.concept.uri]}, self.collection.created_by)
self.expansion.refresh_from_db()

def test_expansion_detail_and_list_show_health_to_a_viewer(self):
detail = self.client.get(self.expansion.uri)
listing = self.client.get(self.collection.uri + 'HEAD/expansions/')

self.assertEqual(detail.status_code, 200)
self.assertEqual(detail.data['health'], self.expansion.health)
self.assertTrue(detail.data['health_is_current'])
self.assertEqual(listing.data[0]['health']['state'], self.expansion.health['state'])

def test_versions_list_shows_each_default_expansion_state(self):
version = OrganizationCollectionFactory(
organization=self.collection.organization, version='v1', mnemonic=self.collection.mnemonic)

response = self.client.get(self.collection.uri + 'versions/')

self.assertEqual(response.status_code, 200)
health = {item['id']: item['expansion_health'] for item in response.data}
self.assertEqual(health['HEAD'], {'state': self.expansion.health['state'], 'is_current': True})
self.assertIsNone(health[version.version])

def test_version_detail_shows_its_default_expansion_state(self):
response = self.client.get(self.collection.uri + 'HEAD/')

self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['expansion_health']['state'], self.expansion.health['state'])

def test_version_lists_nested_elsewhere_carry_no_expansion_health(self):
Expansion.objects.filter(id=self.expansion.id).update(health={'state': HEALTHY}, health_is_current=True)
version = OrganizationCollectionFactory(
organization=self.collection.organization, version='v1', mnemonic=self.collection.mnemonic)
self.expansion.evaluated_collection_versions.add(version)

response = self.client.get(self.expansion.uri)

self.assertNotIn('expansion_health', response.data['evaluated_collection_versions'][0])

def test_member_list_adds_each_members_class_only_when_asked(self):
url = self.expansion.uri + 'concepts/'

plain = self.client.get(url)
with_health = self.client.get(url + '?includeHealth=true')

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): two paths this PR serves have no test:

  • The verbose versions list: CollectionVersionDetailSerializer on the annotated queryset.
  • Mappings with includeHealth: health_resource_type = 'mappings'.

A one-assertion test each would cover them.


self.assertNotIn('health', plain.data[0])
member = with_health.data[0]
self.assertIn(member['health']['class'], ('head', 'mismatch', 'release', 'unreleased'))
self.assertEqual(len(member['health']['references']), 1)
self.assertTrue(member['health']['references'][0].startswith(self.collection.uri + 'references/'))

def test_verbose_versions_list_shows_each_default_expansion_state(self):
response = self.client.get(self.collection.uri + 'versions/?verbose=true')

self.assertEqual(response.status_code, 200)
head = next(item for item in response.data if item['id'] == 'HEAD')
self.assertEqual(head['expansion_health']['state'], self.expansion.health['state'])

def test_version_export_leaves_out_expansion_health(self):
from core.collections.serializers import CollectionVersionExportSerializer
self.assertNotIn('expansion_health', CollectionVersionExportSerializer.Meta.fields)

def test_mapping_list_adds_each_members_class_when_asked(self):
from_concept, to_concept = ConceptFactory(), ConceptFactory()
mapping = MappingFactory(parent=from_concept.parent, from_concept=from_concept, to_concept=to_concept)
self.collection.add_expressions({'expressions': [mapping.uri]}, self.collection.created_by)

response = self.client.get(self.expansion.uri + 'mappings/?includeHealth=true')

self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.data), 1)
self.assertIn('class', response.data[0]['health'])
self.assertEqual(len(response.data[0]['health']['references']), 1)

def test_member_list_gives_each_row_its_own_class(self):
# a member of a release, next to the HEAD member from setUp, so swapped rows would show
second = ConceptFactory()
release = OrganizationSourceFactory(
mnemonic=second.parent.mnemonic, organization=second.parent.organization, version='v1', released=True)
second.get_latest_version().sources.add(release)
self.collection.add_expressions(
{'expressions': [f'{release.uri}concepts/{second.mnemonic}/']}, self.collection.created_by)
classes = ExpansionHealth(self.expansion).classify('concepts')
self.assertEqual(len({member_class for member_class, _, _ in classes.values()}), 2)

response = self.client.get(self.expansion.uri + 'concepts/?includeHealth=true')

self.assertEqual(len(response.data), 2)
for item in response.data:
self.assertEqual(item['health']['class'], classes[int(item['uuid'])][0])

@patch('core.common.utils.get_export_service')
def test_versions_list_csv_export_carries_no_health_annotation(self, export_service):
export_service.return_value.url_for.return_value = 'https://csv-url'

response = self.client.get(
self.collection.uri + 'versions/?csv=true',
HTTP_AUTHORIZATION=f'Token {self.collection.created_by.get_token()}')

# djqscsv writes the queryset's values(), which can't carry the health annotation
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, {'url': 'https://csv-url'})

def test_member_list_ignores_include_health_with_the_toggle_off(self):
with patch.object(Expansion, 'is_health_on', return_value=False):
response = self.client.get(self.expansion.uri + 'concepts/?includeHealth=true')

self.assertNotIn('health', response.data[0])
38 changes: 35 additions & 3 deletions core/collections/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
from core.collections.utils import is_version_specified
from core.common.constants import (
HEAD, RELEASED_PARAM, PROCESSING_PARAM, OK_MESSAGE,
ACCESS_TYPE_NONE, INCLUDE_RETIRED_PARAM, INCLUDE_INVERSE_MAPPINGS_PARAM, ALL, LATEST, DEPRECATED_API_HEADER)
ACCESS_TYPE_NONE, INCLUDE_RETIRED_PARAM, INCLUDE_INVERSE_MAPPINGS_PARAM, ALL, LATEST, DEPRECATED_API_HEADER,
INCLUDE_HEALTH)
from core.common.exceptions import Http409, Http405, Http400
from core.common.mixins import (
ConceptDictionaryCreateMixin, ListWithHeadersMixin, ConceptDictionaryUpdateMixin,
Expand All @@ -55,11 +56,11 @@
from core.common.serializers import TaskSerializer
from core.common.swagger_parameters import q_param, compress_header, page_param, verbose_param, \
include_facets_header, sort_asc_param, sort_desc_param, updated_since_param, include_retired_param, limit_param, \
canonical_url_param, all_versions_param, include_summary_param
canonical_url_param, all_versions_param, include_summary_param, include_health_param
from core.common.tasks import add_references, export_collection, delete_collection, index_expansion_concepts, \
index_expansion_mappings, seed_children_to_expansion, collection_version_compare, expansion_compare
from core.common.throttling import ThrottleUtil
from core.common.utils import compact_dict_by_values, parse_boolean_query_param, to_int
from core.common.utils import compact_dict_by_values, parse_boolean_query_param, get_truthy_values, to_int
from core.common.views import BaseAPIView, BaseLogoView, ConceptContainerExtraRetrieveUpdateDestroyView
from core.concepts.documents import ConceptDocument
from core.concepts.models import Concept
Expand Down Expand Up @@ -832,6 +833,8 @@ def get_queryset(self):
queryset = super().get_queryset()
if self.released_filter is not None:
queryset = queryset.filter(released=self.released_filter)
if not self.request.query_params.get('csv'): # djqscsv can't write values() that carry annotations
queryset = Collection.annotate_expansion_health(queryset)
return queryset.order_by('-created_at')


Expand Down Expand Up @@ -1082,14 +1085,39 @@ def post(self, request, **kwargs): # pylint: disable=unused-argument


class CollectionVersionExpansionChildrenView(CollectionVersionExpansionBaseView, ListWithHeadersMixin):
health_resource_type = None

def get_queryset(self):
expansion = super().get_queryset().first()

if not expansion:
raise Http404()

self.expansion = expansion # pylint: disable=attribute-defined-outside-init
return expansion

def serialize_list(self, results, paginator=None):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): includeHealth isn't documented. Other include* parameters are declared through swagger_auto_schema(manual_parameters=[...]), so /swagger/ shows no way to get member classes. Add an include_health_param and attach it to the concepts and mappings list views' get.

data = super().serialize_list(results, paginator)
if self.request.query_params.get(INCLUDE_HEALTH) in get_truthy_values() and Expansion.is_health_on():
self.add_member_health(results, data['results'] if isinstance(data, dict) else data)
return data

def add_member_health(self, members, items):
"""Each member of this page gets its class and the references that judged it, computed for this page"""
from core.collections.health import ExpansionHealth
members = list(members)
classes = ExpansionHealth(self.expansion).classify(self.health_resource_type, [member.id for member in members])
references_uri = f'{self.expansion.collection_version.uri}references/'
for member, item in zip(members, items):
# by the row's own id where it has one; the serializer keeps the page's order, so position matches too
member_id = int(item['uuid']) if item.get('uuid') else member.id
member_class, reference_ids, _ = classes.get(member_id, (None, [], False))
item['health'] = {
'class': member_class,
'references': [f'{references_uri}{reference_id}/' for reference_id in reference_ids]
}

@swagger_auto_schema(manual_parameters=[include_health_param])
def get(self, request, *args, **kwargs):
self.get_queryset()
return self.list(request, *args, **kwargs)
Expand All @@ -1107,6 +1135,8 @@ class CollectionVersionExpansionConceptsView(CollectionVersionExpansionChildrenV
facet_class = ConceptFacetedSearch
default_qs_sort_attr = '-id'

health_resource_type = 'concepts'

def get_serializer_class(self):
from core.concepts.serializers import ConceptDetailSerializer, ConceptListSerializer
return ConceptDetailSerializer if self.is_verbose() else ConceptListSerializer
Expand All @@ -1123,6 +1153,8 @@ class CollectionVersionExpansionMappingsView(CollectionVersionExpansionChildrenV
facet_class = MappingFacetedSearch
default_qs_sort_attr = '-id'

health_resource_type = 'mappings'

def get_serializer_class(self):
from core.mappings.serializers import MappingDetailSerializer, MappingListSerializer
return MappingDetailSerializer if self.is_verbose() else MappingListSerializer
Expand Down
3 changes: 2 additions & 1 deletion core/common/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
INCLUDE_EXTERNAL_EXPORTS = 'includeExternalExports'
INCLUDE_LOGS = 'includeLogs'
INCLUDE_STATES = 'includeStates'
INCLUDE_HEALTH = 'includeHealth'
INCLUDE_TASKS = 'includeTasks'
INCLUDE_VERBOSE_REFERENCES = 'includeReferences'
INCLUDE_AUTH_GROUPS = 'includeAuthGroups'
Expand Down Expand Up @@ -169,4 +170,4 @@
VERIFICATION_INVALID = 'Must have exactly verified_at (ISO 8601 date-time with seconds and Z or an offset), ' \
'process (1 to 64 letters, digits, . and -) and hash (sha256: and 64 lowercase hex characters).'
VERIFICATION_ONLY_ON_VERSION = 'Can only be set on an existing repository version, not on HEAD.'
VERSION_EXPORT_EXCLUDED_FIELDS = {'verification'}
VERSION_EXPORT_EXCLUDED_FIELDS = {'verification', 'expansion_health'}
6 changes: 5 additions & 1 deletion core/common/swagger_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
LAST_LOGIN_BEFORE_PARAM, LAST_LOGIN_SINCE_PARAM, DATE_JOINED_SINCE_PARAM, DATE_JOINED_BEFORE_PARAM, \
CASCADE_HIERARCHY_PARAM, CASCADE_METHOD_PARAM, MAP_TYPES_PARAM, EXCLUDE_MAP_TYPES_PARAM, CASCADE_MAPPINGS_PARAM, \
INCLUDE_MAPPINGS_PARAM, CASCADE_LEVELS_PARAM, CASCADE_DIRECTION_PARAM, ALL, RETURN_MAP_TYPES, OMIT_IF_EXISTS_IN, \
EQUIVALENCY_MAP_TYPES, CANONICAL_URL_REQUEST_PARAM, INCLUDE_SUMMARY
EQUIVALENCY_MAP_TYPES, CANONICAL_URL_REQUEST_PARAM, INCLUDE_SUMMARY, INCLUDE_HEALTH
# HEADERS
from core.orgs.constants import NO_MEMBERS

Expand Down Expand Up @@ -215,6 +215,10 @@
INCLUDE_SUMMARY, openapi.IN_QUERY, type=openapi.TYPE_BOOLEAN, default=False,
description='Include summary counts of active concepts and mappings'
)
include_health_param = openapi.Parameter(
INCLUDE_HEALTH, openapi.IN_QUERY, type=openapi.TYPE_BOOLEAN, default=False,
description="Include each member's health class and the references that judged it, for this page"
)

task_state_param = openapi.Parameter(
'state',
Expand Down
Loading