diff --git a/core/celery.py b/core/celery.py index 26b34e95c..c2220992f 100644 --- a/core/celery.py +++ b/core/celery.py @@ -29,6 +29,10 @@ 'task': 'core.common.tasks.vacuum_and_analyze_db', 'schedule': crontab(0, 1), # Run at 1 am }, + 'recheck-expansion-health': { + 'task': 'core.common.tasks.recheck_expansion_health', + 'schedule': crontab(0, 2), # Run at 2 am + }, 'expire-celery-tasks': { 'task': 'core.common.tasks.expire_old_celery_tasks', 'schedule': crontab(0, 1), # Run at 1 am diff --git a/core/collections/constants.py b/core/collections/constants.py index 820427a3e..585043ce6 100644 --- a/core/collections/constants.py +++ b/core/collections/constants.py @@ -48,6 +48,11 @@ UNRESOLVED_RESOURCE_VERSION_TYPE = 'reference.resource_version' INTENSIONAL_REFERENCE_RESOURCE_VERSIONS_TOGGLE = 'INTENSIONAL_REFERENCE_RESOURCE_VERSIONS_TOGGLE' EXPANSION_LOCKED_REPO_VERSION_TOGGLE = 'EXPANSION_LOCKED_REPO_VERSION_TOGGLE' +EXPANSION_HEALTH_TOGGLE = 'EXPANSION_HEALTH_TOGGLE' +EXPANSION_HEALTH_DEBOUNCE_SECONDS = 60 +# a repo version's fields that expansion health reads +HEALTH_RELEVANT_VERSION_FIELDS = {'released', 'retired', 'is_active', 'public_access', 'expansion_uri'} +EXPANSION_HEALTH_RECHECK_LIMIT = 1000 VERSION_EXPANSION_LOCK = 'lock' VERSION_EXPANSION_LATEST = 'latest' VERSION_EXPANSION_NONE = 'none' diff --git a/core/collections/migrations/0074_expansion_health.py b/core/collections/migrations/0074_expansion_health.py new file mode 100644 index 000000000..d8e9807d9 --- /dev/null +++ b/core/collections/migrations/0074_expansion_health.py @@ -0,0 +1,26 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('collections', '0073_collection_verification'), + ] + + operations = [ + migrations.AddField( + model_name='expansion', + name='health', + field=models.JSONField(blank=True, null=True), + ), + migrations.AddField( + model_name='expansion', + name='health_is_current', + field=models.BooleanField(blank=True, null=True), + ), + migrations.AddField( + model_name='expansion', + name='health_revision', + field=models.IntegerField(default=0), + ), + ] diff --git a/core/collections/models.py b/core/collections/models.py index 233b58f00..c8759f3f4 100644 --- a/core/collections/models.py +++ b/core/collections/models.py @@ -1,3 +1,4 @@ +import logging import time from contextlib import nullcontext @@ -19,7 +20,8 @@ TRANSFORM_TO_RESOURCE_VERSIONS, COLLECTION_REFERENCE_TYPE, TRANSFORM_TO_EXTENSIONAL, RESOURCE_VERSION_REPO_RESOLUTION_TOGGLE, UNRESOLVED_RESOURCE_VERSION_TYPE, INTENSIONAL_REFERENCE_RESOURCE_VERSIONS_TOGGLE, EXPANSION_LOCKED_REPO_VERSION_TOGGLE, VERSION_EXPANSION_LOCK, - VERSION_EXPANSION_LATEST, REFERENCE_FOUND_NOTHING, REFERENCE_VERSION_NOT_HELD, REFERENCE_EXCLUDED_BY_PARAMETERS) + VERSION_EXPANSION_LATEST, REFERENCE_FOUND_NOTHING, REFERENCE_VERSION_NOT_HELD, REFERENCE_EXCLUDED_BY_PARAMETERS, + EXPANSION_HEALTH_TOGGLE, EXPANSION_HEALTH_DEBOUNCE_SECONDS, HEALTH_RELEVANT_VERSION_FIELDS) from core.collections.parsers import CollectionReferenceParser from core.collections.translators import CollectionReferenceTranslator from core.collections.utils import is_concept, is_mapping @@ -32,7 +34,7 @@ from core.common.models import ConceptContainerModel, BaseResourceModel from core.common.search import CustomESSearch from core.common.tasks import seed_children_to_expansion, batch_index_resources, index_expansion_concepts, \ - index_expansion_mappings, readd_references_to_expansion_on_references_removal + index_expansion_mappings, readd_references_to_expansion_on_references_removal, compute_expansion_health from core.common.utils import drop_version, to_owner_uri, generate_temp_version, es_id_in, \ get_resource_class_from_resource_name, to_snake_case, \ es_to_pks, id_batches, split_list_by_condition, decode_string, is_canonical_uri, encode_string, \ @@ -47,6 +49,7 @@ TRUTHY = get_truthy_values() FALSEY = get_falsy_values() +logger = logging.getLogger('oclapi') class Collection(DirtyFieldsMixin, VersionCompareMixin, ConceptContainerModel): @@ -167,6 +170,7 @@ def should_auto_expand(self): def save( self, *args, force_insert=False, force_update=False, using=None, update_fields=None ): + is_new = not self.id dirty_fields = self.get_dirty_fields() super().save(*args, force_insert=force_insert, force_update=force_update, using=using, @@ -174,6 +178,8 @@ def save( if self.id and 'canonical_url' in dirty_fields: self.resolve_url_registry_entries_later() + if self.id and not is_new and HEALTH_RELEVANT_VERSION_FIELDS & set(dirty_fields): + Expansion.mark_health_not_current_for_repository(self) def post_create_actions(self): if self.should_auto_expand: @@ -297,7 +303,12 @@ def add_references(self, references, user=None, _async=False): added_references.append(reference) if self.expansion_uri: - self.expansion.add_references(added_references) + expansion = self.expansion + expansion.add_references(added_references) + if added_references: + expansion.mark_health_out_of_date() + if added_references: + Expansion.mark_health_not_current_for_value_set(self) self.__dict__.pop('locked_source_versions', None) self.__dict__.pop('locked_collection_versions', None) if user and user.is_authenticated: @@ -328,9 +339,13 @@ def delete_references(self, expressions): if expressions == ALL: # Deprecated: Old way # one transaction, so no one sees the expansion emptied while the references remain with CollectionReference.atomic_when_locked(): - if self.expansion_uri: - self.expansion.delete_expressions(expressions) + expansion = self.expansion if self.expansion_uri else None + if expansion: + expansion.delete_expressions(expressions) self.references.all().delete() + if expansion: + expansion.mark_health_out_of_date() + Expansion.mark_health_not_current_for_value_set(self) return self.remove_references(self.references.filter(expression__in=expressions)) @@ -338,9 +353,13 @@ def delete_references(self, expressions): def remove_references(self, references): """Members and references go in one transaction, so no one sees one gone without the other""" with CollectionReference.atomic_when_locked(): - if self.expansion_uri: - self.expansion.delete_references(references) + expansion = self.expansion if self.expansion_uri else None + if expansion: + expansion.delete_references(references) references.delete() + if expansion: + expansion.mark_health_out_of_date() + Expansion.mark_health_not_current_for_value_set(self) def get_cascaded_mapping_uris_from_concept_expressions(self, expressions): mapping_uris = [] @@ -380,6 +399,11 @@ def cascade_children_to_expansion(self, expansion_data=None, index=True, sync=Fa elif should_auto_expand and not self.expansion_uri: self.expansion_uri = expansion.uri self.save() + # a seed that ended before this made it the default stored no health + if Expansion.objects.filter(id=expansion.id, is_processing=False, health_is_current__isnull=True).exists(): + # the seed saved what it found (unresolved repositories among it) on its own copy + expansion.refresh_from_db() + expansion.update_health() return expansion @@ -424,6 +448,7 @@ def seed_from_head_expansion(self, lock=True, index=True): self.refresh_from_db() self.__dict__.pop('locked_source_versions', None) self.__dict__.pop('locked_collection_versions', None) + expansion.update_health() if index: expansion.index_resources( list(expansion.concepts.values_list('id', flat=True)), @@ -1617,6 +1642,12 @@ class Meta: built_with = models.CharField( max_length=10, null=True, blank=True, choices=[(choice, choice) for choice in (VERSION_EXPANSION_LOCK, VERSION_EXPANSION_LATEST)]) + # the summary core.collections.health computes (null: never computed), and whether it matches the members now + health = models.JSONField(null=True, blank=True) + health_is_current = models.BooleanField(null=True, blank=True) + # bumped by every mark, so a computation that started before a change can't store its result as current + health_revision = models.IntegerField(default=0) + HEALTH_FIELDS = ('health', 'health_is_current', 'health_revision') @property def is_head(self): @@ -2521,6 +2552,143 @@ def _get_resources_index_collection_fields(self): 'collection_owner_url': [self.owner_url], } + def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None): + if update_fields is None and not force_insert and not self._state.adding: + # health is written only by its own updates, so a save from an older copy can't undo them + update_fields = [ + field.name for field in self._meta.concrete_fields + if not field.primary_key and field.name not in self.HEALTH_FIELDS] + super().save(*args, force_insert=force_insert, force_update=force_update, using=using, + update_fields=update_fields) + + @staticmethod + def is_health_on(): + return bool(Toggle.get(EXPANSION_HEALTH_TOGGLE)) + + def update_health(self): + """Computes and saves the health summary of a version's default expansion, the only one health is kept for + for now. Stored as current only if nothing marked it while it computed. A failure is logged and leaves it + out of date; it never fails the build that called it""" + if not self.is_health_on(): + return None + from core.collections.health import ExpansionHealth + expansions = Expansion.objects.filter(id=self.id) + if not self.is_default: + expansions.update(health=None, health_is_current=None) + self.health = None + return None + revision = expansions.values_list('health_revision', flat=True).first() + if revision is None: + return None + try: + health = ExpansionHealth(self).compute() + except Exception: # pylint: disable=broad-except + logger.exception('Expansion health failed for %s', self.uri) + # None, not False: nothing is queued, so the next change queues a recompute + expansions.filter(health_revision=revision).update(health_is_current=None) + return None + # the store bumps it too, so an older run that ends after a newer one (a rebuild's) can't overwrite it + if not expansions.filter(health_revision=revision).update( + health=health, health_is_current=True, health_revision=F('health_revision') + 1): + # marked, or stored by a newer run, while it computed: a fresh run reads the change + self.queue_health_recompute(self.id) + return None + self.health = health + self.health_is_current = True + return health + + @staticmethod + def queue_health_recompute(expansion_id): + """One debounced recompute once the caller's transaction commits. A failure to queue leaves it not current + with nothing queued (None), so the next change queues one""" + if get(settings, 'TEST_MODE', False): + compute_expansion_health(expansion_id) + return + + def queue_recompute(): + try: + compute_expansion_health.apply_async( + (expansion_id,), queue='default', countdown=EXPANSION_HEALTH_DEBOUNCE_SECONDS) + except Exception: # pylint: disable=broad-except + logger.exception('Could not queue expansion health for %s', expansion_id) + Expansion.objects.filter(id=expansion_id, health_is_current=False).update(health_is_current=None) + + transaction.on_commit(queue_recompute) + + @classmethod + def mark_health_not_current(cls, expansion_ids): + """Not current, with nothing queued: the next change, the nightly recheck or the backfill computes them. One + already out of date (False) keeps its queued run. Marked whatever the toggle, as it costs one update""" + if expansion_ids: + cls.objects.filter(id__in=expansion_ids).update( + health_revision=F('health_revision') + 1, health_is_current=models.Case( + models.When(health_is_current=False, then=models.Value(False)), default=models.Value(None), + output_field=models.BooleanField(null=True))) + + @classmethod + def mark_health_not_current_for_repository(cls, repo_version): + """Expansions that recorded a version of repo_version's repository: their classes read its versions, so a + release, retire, visibility change or delete leaves them not current. Returns their ids""" + kind = 'collection' if isinstance(repo_version, Collection) else 'source' + version_ids = repo_version.versions.values('id') + expansion_ids = list(cls.objects.filter( + models.Q(**{f'explicit_{kind}_versions__in': version_ids}) | + models.Q(**{f'evaluated_{kind}_versions__in': version_ids}) + ).values_list('id', flat=True).distinct()) + cls.mark_health_not_current(expansion_ids) + return expansion_ids + + @classmethod + def mark_health_not_current_for_value_set(cls, collection_version): + """Expansions whose value-set references were judged against this collection version's expansion""" + cls.mark_health_not_current(list(cls.objects.filter( + models.Q(explicit_collection_versions=collection_version) | + models.Q(evaluated_collection_versions=collection_version) + ).values_list('id', flat=True).distinct())) + + @classmethod + def mark_health_not_current_for_members(cls, resource_type, member_ids): + """Expansions holding these concepts or mappings, before a hard delete takes the membership rows""" + cls.mark_health_not_current(list(cls.objects.filter( + **{f'{resource_type}__id__in': member_ids}).values_list('id', flat=True).distinct())) + + @classmethod + def mark_health_out_of_date_for_members(cls, resource_type, member_ids): + """A member leaving or re-entering HEAD changes its class. The default expansions holding it are marked out + of date, and each that wasn't already is recomputed, as a frozen release would otherwise never be""" + if not member_ids: + return + expansion_ids = list(cls.objects.filter( + collection_version__expansion_uri=F('uri'), **{f'{resource_type}__id__in': member_ids} + ).values_list('id', flat=True).distinct()) + if not expansion_ids: + return + if not cls.is_health_on(): + cls.mark_health_not_current(expansion_ids) + return + expansions = cls.objects.filter(id__in=expansion_ids) + # bumped first, as mark_health_out_of_date does, then the ones not already out of date are flipped and queued + expansions.update(health_revision=F('health_revision') + 1) + queued_ids = list(expansions.exclude(health_is_current=False).values_list('id', flat=True)) + cls.objects.filter(id__in=queued_ids).update(health_is_current=False) + for expansion_id in queued_ids: + cls.queue_health_recompute(expansion_id) + + def mark_health_out_of_date(self): + """Marks the health out of date and queues one recompute, however many changes follow before it runs. With the + toggle off it is only marked not current, so the backfill finds it once health is on again""" + expansions = Expansion.objects.filter(id=self.id) + bump = F('health_revision') + 1 + if not self.is_health_on(): + expansions.update(health_is_current=None, health_revision=bump) + self.health_is_current = None + return + self.health_is_current = False + # bumped on its own first, so a run that read the old revision can't then store its result as current + expansions.update(health_revision=bump) + if expansions.exclude(health_is_current=False).update(health_is_current=False): + self.queue_health_recompute(self.id) + def clear_processing(self, full_save=False): if self.is_processing: self.is_processing = False diff --git a/core/collections/tests/tests.py b/core/collections/tests/tests.py index 9314fbe6d..39cf74a72 100644 --- a/core/collections/tests/tests.py +++ b/core/collections/tests/tests.py @@ -2605,6 +2605,7 @@ def test_seed_children_task_evaluates_references_while_head_expansion_is_process self.assertEqual(list(copy.concepts.all()), [latest]) self.assertEqual(list(collection_v1.references.first().concepts.all()), [latest]) + @patch('core.collections.models.Expansion.is_health_on', Mock(return_value=False)) @patch('core.collections.models.batch_index_resources') @patch('core.collections.models.readd_references_to_expansion_on_references_removal') @patch('core.common.tasks.export_collection') @@ -2790,6 +2791,7 @@ def test_manual_expansion_resolves_valuesets_under_its_own_lock(self): self.assertEqual(list(manual.concepts.all()), expected) self.assertIsNone(references[0]._valueset_locks) # pylint: disable=protected-access + @patch('core.collections.models.Expansion.is_health_on', Mock(return_value=False)) @override_settings(TEST_MODE=False) @patch('core.collections.models.batch_index_resources') @patch('core.collections.models.readd_references_to_expansion_on_references_removal') @@ -2828,6 +2830,7 @@ def collection_with_referenced_member(): reference.concepts.add(concept) return collection, expansion, reference + @patch('core.collections.models.Expansion.is_health_on', Mock(return_value=False)) @override_settings(TEST_MODE=False) @patch('core.collections.models.batch_index_resources') @patch('core.collections.models.readd_references_to_expansion_on_references_removal') @@ -2849,6 +2852,7 @@ def test_remove_references_with_toggle_off_queues_at_once_before_deleting(self, self.assertFalse( Task.objects.filter(name__iendswith='readd_references_to_expansion_on_references_removal').exists()) + @patch('core.collections.models.Expansion.is_health_on', Mock(return_value=False)) @override_settings(TEST_MODE=False) @patch('core.collections.models.batch_index_resources') @patch('core.collections.models.readd_references_to_expansion_on_references_removal') diff --git a/core/collections/tests/tests_health.py b/core/collections/tests/tests_health.py index c40c8d4c5..d84eb2658 100644 --- a/core/collections/tests/tests_health.py +++ b/core/collections/tests/tests_health.py @@ -1,6 +1,8 @@ from django.db import connection +from django.db.models import F +from django.test import override_settings from django.test.utils import CaptureQueriesContext -from mock import patch +from mock import patch, Mock from core.collections.health import ( ExpansionHealth, RELEASE, UNRELEASED, HEAD_MEMBER, INTERIM, MISMATCH, AMBIGUOUS, @@ -8,6 +10,7 @@ from core.collections.models import CollectionReference, Expansion 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.concepts.tests.factories import ConceptFactory from core.mappings.tests.factories import MappingFactory @@ -584,3 +587,313 @@ def count_queries(releases_count): # another owner's public versions: their visibility is one query, not one per version self.assertEqual(count_queries(2), count_queries(6)) + + +class ExpansionHealthStorageTest(OCLTestCase): + def setUp(self): + super().setUp() + self.collection = OrganizationCollectionFactory() + # the default before it seeds, as a version's own build makes it, so the seed stores health + self.expansion = Expansion.persist( + index=False, collection_version=self.collection, mnemonic='autoexpand-HEAD', claim_default=True) + self.assertEqual(self.collection.expansion_uri, self.expansion.uri) + + def add(self, *concepts): + self.collection.add_expressions( + {'expressions': [concept.uri for concept in concepts]}, self.collection.created_by) + + def stored(self): + return Expansion.objects.values_list('health', 'health_is_current').get(id=self.expansion.id) + + def test_build_stores_health(self): + health, is_current = self.stored() + self.assertTrue(is_current) + self.assertEqual(health['state'], EMPTY) + self.assertEqual(health['rules_version'], 1) + + def test_adding_references_recomputes_health(self): + self.add(ConceptFactory()) + + health, is_current = self.stored() + self.assertTrue(is_current) + self.assertNotEqual(health['state'], EMPTY) + + def test_removing_references_recomputes_health(self): + concept = ConceptFactory() + self.add(concept) + + self.collection.delete_references([concept.uri]) + + health, is_current = self.stored() + self.assertTrue(is_current) + self.assertEqual(health['state'], EMPTY) + + def test_one_add_of_many_references_recomputes_once(self): + with patch.object(ExpansionHealth, 'compute', return_value={'state': HEALTHY}) as compute: + self.add(ConceptFactory(), ConceptFactory(), ConceptFactory()) + + compute.assert_called_once() + + def test_an_expansion_already_out_of_date_queues_no_second_recompute(self): + Expansion.objects.filter(id=self.expansion.id).update(health_is_current=False) + + with patch.object(ExpansionHealth, 'compute') as compute: + self.add(ConceptFactory()) + + compute.assert_not_called() + self.assertFalse(self.stored()[1]) + + def test_toggle_off_marks_the_change_and_computes_nothing(self): + before = self.stored()[0] + with patch.object(Expansion, 'is_health_on', return_value=False), \ + patch.object(ExpansionHealth, 'compute') as compute: + self.add(ConceptFactory()) + + # marked not current, so the backfill finds it once health is on again; the stored summary is untouched + self.assertEqual(self.stored(), (before, None)) + compute.assert_not_called() + + def test_health_is_kept_for_the_default_expansion_only(self): + other = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + + self.assertIsNone(other.update_health()) + self.assertEqual(Expansion.objects.values_list('health', 'health_is_current').get(id=other.id), (None, None)) + self.assertTrue(self.stored()[1]) + + def test_a_change_while_it_computes_is_not_stored_as_current(self): + computed = [] + + def compute(_health): + if not computed: # the first run is overtaken by a change + Expansion.objects.filter(id=self.expansion.id).update(health_revision=F('health_revision') + 1) + computed.append(1) + return {'state': HEALTHY, 'run': len(computed)} + + with patch.object(ExpansionHealth, 'compute', autospec=True, side_effect=compute): + Expansion.objects.get(id=self.expansion.id).update_health() + + # the overtaken run stored nothing; the run it queued read the change and is current + self.assertEqual(self.stored(), ({'state': HEALTHY, 'run': 2}, True)) + + def test_a_failure_to_queue_leaves_health_not_current_so_the_next_change_queues(self): + with override_settings(TEST_MODE=False), \ + patch('core.collections.models.compute_expansion_health.apply_async', side_effect=OSError('down')), \ + self.captureOnCommitCallbacks(execute=True): + Expansion.objects.get(id=self.expansion.id).mark_health_out_of_date() + + self.assertIsNone(self.stored()[1]) + + def test_a_failure_leaves_health_out_of_date_and_the_build_done(self): + before = self.stored()[0] + with patch.object(ExpansionHealth, 'compute', side_effect=ValueError('boom')): + self.expansion.seed_children(index=False) + self.expansion.update_health() + + expansion = Expansion.objects.get(id=self.expansion.id) + self.assertFalse(expansion.is_processing) + self.assertEqual((expansion.health, expansion.health_is_current), (before, None)) + + def test_a_change_after_a_failure_recomputes(self): + with patch.object(ExpansionHealth, 'compute', side_effect=ValueError('boom')): + self.add(ConceptFactory()) + self.assertIsNone(self.stored()[1]) + + self.add(ConceptFactory()) + + health, is_current = self.stored() + self.assertTrue(is_current) + self.assertNotEqual(health['state'], EMPTY) + + def recorded_source_version(self, **kwargs): + source = OrganizationSourceFactory() + version = OrganizationSourceFactory( + mnemonic=source.mnemonic, organization=source.organization, version='v1', is_latest_version=False, + **kwargs) + self.expansion.evaluated_source_versions.add(source) + # the default expansion of a collection that records nothing of the source + other_collection = OrganizationCollectionFactory() + other = Expansion.persist(index=False, collection_version=other_collection, mnemonic='autoexpand-HEAD') + other_collection.expansion_uri = other.uri + other_collection.save() + other.update_health() + return version, other + + def test_releasing_a_version_of_a_recorded_repository_leaves_health_not_current(self): + version, other = self.recorded_source_version(released=False) + + version.released = True + version.save() + + self.assertIsNone(self.stored()[1]) + self.assertTrue(Expansion.objects.get(id=other.id).health_is_current) + + def test_retiring_a_version_of_a_recorded_repository_leaves_health_not_current(self): + version, _ = self.recorded_source_version(released=True) + + version.retired = True + version.save() + + self.assertIsNone(self.stored()[1]) + + def test_making_a_recorded_repository_private_leaves_health_not_current(self): + version, _ = self.recorded_source_version(released=True) + + version.public_access = ACCESS_TYPE_NONE + version.save() + + self.assertIsNone(self.stored()[1]) + + def test_a_save_that_changes_no_health_field_keeps_health_current(self): + version, _ = self.recorded_source_version(released=True) + + version.description = 'changed' + version.save() + + self.assertTrue(self.stored()[1]) + + @patch('core.common.models.delete_s3_objects', Mock()) + def test_deleting_a_version_of_a_recorded_repository_leaves_health_not_current(self): + version, _ = self.recorded_source_version(released=True) + + version.delete() + + self.assertIsNone(self.stored()[1]) + + @patch('core.common.models.delete_s3_objects', Mock()) + def test_a_recompute_that_ran_before_a_delete_committed_is_not_left_current(self): + version, _ = self.recorded_source_version(released=True) + + with self.captureOnCommitCallbacks(execute=True): + version.delete() + # a recompute stores its result before the delete commits + Expansion.objects.filter(id=self.expansion.id).update(health_is_current=True) + + self.assertIsNone(self.stored()[1]) + + def test_a_change_to_a_value_set_leaves_expansions_judged_against_it_not_current(self): + value_set = OrganizationCollectionFactory() + value_set_expansion = Expansion.persist(index=False, collection_version=value_set, mnemonic='autoexpand-HEAD') + value_set.expansion_uri = value_set_expansion.uri + value_set.save() + self.expansion.evaluated_collection_versions.add(value_set) + self.assertTrue(self.stored()[1]) + + value_set.add_expressions({'expressions': [ConceptFactory().uri]}, value_set.created_by) + + self.assertIsNone(self.stored()[1]) + + def test_editing_a_member_in_head_recomputes_the_expansions_holding_it(self): + concept = ConceptFactory() + member = concept.get_latest_version() + # a reference to the version itself: one to the concept would hold the HEAD concept + self.add(member) + self.assertEqual(self.stored()[0]['members']['concepts'][HEAD_MEMBER], 1) + + # the edit takes the old version out of HEAD, so the member it was is now interim + member.unmark_latest_version() + + health, is_current = self.stored() + self.assertTrue(is_current) + self.assertEqual(health['members']['concepts'][INTERIM], 1) + + def test_a_seed_that_ends_before_its_expansion_is_the_default_still_stores_health(self): + collection = OrganizationCollectionFactory() + CollectionReference( + expression='/orgs/missing/sources/missing/concepts/c1/', collection=collection, + system='/orgs/missing/sources/missing/', code='c1').save() + with patch.object(CollectionReference, 'is_expansion_locked_repo_version_on', return_value=False): + collection.cascade_children_to_expansion(index=False) + + expansion = collection.expansion + self.assertTrue(expansion.health_is_current) + # computed from what the seed saved, the reference it couldn't resolve among it + reasons = {reason['code']: reason['count'] for reason in expansion.health['reasons']} + self.assertEqual(reasons.get('unresolved_references'), 1) + + def test_dropping_unseen_children_from_head_recomputes_the_expansions_holding_them(self): + concept = ConceptFactory() + member = concept.get_latest_version() + self.add(member) + self.assertEqual(self.stored()[0]['members']['concepts'][HEAD_MEMBER], 1) + + with patch('core.sources.models.Source.queue_index_dropped_children'): + concept.parent.drop_unseen_children([], []) + + health, is_current = self.stored() + self.assertTrue(is_current) + self.assertEqual(health['members']['concepts'][INTERIM], 1) + + def test_a_hard_deleted_member_leaves_the_expansions_holding_it_not_current(self): + concept = ConceptFactory() + self.add(concept) + self.assertTrue(self.stored()[1]) + + concept.delete() + + self.assertIsNone(self.stored()[1]) + + def test_the_nightly_recheck_recomputes_default_expansions_that_are_not_current(self): + other = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + Expansion.objects.filter(id__in=[self.expansion.id, other.id]).update(health=None, health_is_current=None) + + self.assertEqual(recheck_expansion_health(), 1) + + self.assertTrue(self.stored()[1]) + self.assertEqual(Expansion.objects.values_list('health_is_current', flat=True).get(id=other.id), None) + + def test_the_nightly_recheck_also_takes_ones_whose_queued_run_never_came(self): + Expansion.objects.filter(id=self.expansion.id).update(health_is_current=False) + + self.assertEqual(recheck_expansion_health(), 1) + self.assertTrue(self.stored()[1]) + + def test_a_mark_bumps_the_revision_before_anything_else(self): + Expansion.objects.filter(id=self.expansion.id).update(health_is_current=False) + expansion = Expansion.objects.get(id=self.expansion.id) + + with CaptureQueriesContext(connection) as context: + expansion.mark_health_out_of_date() + + # a run that read the old revision can't store its result between the mark's statements + updates = [query['sql'] for query in context.captured_queries if query['sql'].startswith('UPDATE')] + self.assertIn('"health_revision"', updates[0]) + self.assertNotIn('"health_is_current"', updates[0].split(' WHERE ')[0]) + + def test_an_older_run_that_ends_after_a_newer_store_does_not_overwrite_it(self): + computed = [] + real_compute = ExpansionHealth.compute + + def compute(health): + computed.append(1) + if len(computed) == 1: + # a newer run (a rebuild's) stores while this one computes + Expansion.objects.get(id=self.expansion.id).update_health() + return {'state': HEALTHY, 'stale': True} + return real_compute(health) + + with patch.object(ExpansionHealth, 'compute', autospec=True, side_effect=compute): + Expansion.objects.get(id=self.expansion.id).update_health() + + health, is_current = self.stored() + self.assertTrue(is_current) + self.assertEqual(health['state'], EMPTY) + + def test_a_save_from_an_older_copy_keeps_the_health(self): + older = Expansion.objects.get(id=self.expansion.id) + Expansion.objects.filter(id=self.expansion.id).update(health={'state': HEALTHY}, health_is_current=True) + + older.save() + + self.assertEqual(self.stored(), ({'state': HEALTHY}, True)) + + @patch('core.common.tasks.export_collection') + def test_version_created_from_head_stores_health(self, _): + self.add(ConceptFactory()) + version = OrganizationCollectionFactory( + organization=self.collection.organization, version='v1', mnemonic=self.collection.mnemonic) + + seed_children_to_new_version('collection', version.id, False) # pylint: disable=no-value-for-parameter + + version.refresh_from_db() + self.assertTrue(version.expansion.health_is_current) + self.assertIsNotNone(version.expansion.health['state']) diff --git a/core/common/mixins.py b/core/common/mixins.py index 041bb3bb7..89d24dfd9 100644 --- a/core/common/mixins.py +++ b/core/common/mixins.py @@ -676,6 +676,14 @@ class SourceChildMixin(ChecksumModel): ISOLATED_VERSION_DEFAULTS = {'extras': {}, 'retired': False} + def delete(self, *args, **kwargs): # pylint: disable=arguments-differ + from core.collections.models import Expansion + # the cascade takes the membership rows (a versioned object's, its versions' too), so expansions go first + rows = self.__class__.objects.filter(versioned_object_id=self.id) if self.is_versioned_object else [self] + Expansion.mark_health_not_current_for_members( + f'{self.__class__.__name__.lower()}s', [self.id, *[row.id for row in rows]]) + return super().delete(*args, **kwargs) + # relations the list serializers read on every row, prefetched once per page by load_list_fields LIST_PREFETCHES = () # relations named like the serializer field that reads them; prefetched by load_list_fields when it's serialized @@ -1146,6 +1154,14 @@ def __update_latest_version(self, index, is_latest_version, parent, remove_paren self.sources.remove(parent) if add_parent: self.sources.add(parent) + if remove_parent or add_parent: + self.mark_expansion_health_for_head_change() + + def mark_expansion_health_for_head_change(self, *rows): + """A row leaving or re-entering HEAD changes its class in the expansions that hold it""" + from core.collections.models import Expansion + Expansion.mark_health_out_of_date_for_members( + f'{self.__class__.__name__.lower()}s', [row.id for row in (rows or [self]) if row]) def set_version_fields(self, data, fields, isolated=False): for field in fields: @@ -1166,6 +1182,7 @@ def restore_to_head(self): latest_version = versioned_object.get_latest_version() if latest_version: latest_version.sources.add(parent) + self.mark_expansion_health_for_head_change(versioned_object, latest_version) return latest_version def unmark_latest_version(self, index=True, parent=None): diff --git a/core/common/models.py b/core/common/models.py index 2662e535e..e9221dd4f 100644 --- a/core/common/models.py +++ b/core/common/models.py @@ -981,6 +981,10 @@ def versions(self): ).order_by('-created_at') def delete(self, using=None, keep_parents=False, force=False, sync=False): # pylint: disable=arguments-differ + from core.collections.models import Expansion + # before the rows go, while expansions still record this version; again on commit, whatever their flag then, + # so a recompute that ran before the delete committed isn't left current + health_expansion_ids = Expansion.mark_health_not_current_for_repository(self) export_paths = self.get_export_paths_to_delete() deleted_urls = [self.url] deleted_ids = [self.id] @@ -1011,6 +1015,7 @@ def delete(self, using=None, keep_parents=False, force=False, sync=False): # py self.delete_version_checksum_maps(deleted_urls) super().delete(using=using, keep_parents=keep_parents) + transaction.on_commit(lambda: Expansion.mark_health_not_current(health_expansion_ids)) self.delete_export_paths(export_paths, sync) self.post_delete_actions() self.relink_url_registry_entries(registry_entry_ids, canonical_urls - {None, ''}) diff --git a/core/common/tasks.py b/core/common/tasks.py index 3150f6dbe..ee4fb9e2d 100644 --- a/core/common/tasks.py +++ b/core/common/tasks.py @@ -502,6 +502,34 @@ def seed_children_to_expansion(expansion_id, index=True, force_reevaluate=False) if expansion: expansion.seed_children(index=index, force_reevaluate=force_reevaluate) expansion.clear_processing(True) + expansion.update_health() + + +@app.task(ignore_result=True) +def compute_expansion_health(expansion_id): + from core.collections.models import Expansion + expansion = Expansion.objects.filter(id=expansion_id).first() + if expansion: + expansion.update_health() + + +@app.task(ignore_result=True) +def recheck_expansion_health(limit=None): + """Nightly: recomputes, a batch at a time, the default expansions whose health isn't current. A release, retire + or delete leaves them so, and a frozen release never gets another change. One with a run queued (False) is taken + too, in case that run never came: a duplicate is harmless, as a store checks the revision""" + from django.db.models import F + from core.collections.constants import EXPANSION_HEALTH_RECHECK_LIMIT + from core.collections.models import Expansion + if not Expansion.is_health_on(): + return 0 + expansion_ids = list(Expansion.objects.exclude(health_is_current=True).filter( + is_processing=False, is_active=True, collection_version__is_active=True, + collection_version__expansion_uri=F('uri') + ).order_by('id').values_list('id', flat=True)[:limit or EXPANSION_HEALTH_RECHECK_LIMIT]) + for expansion_id in expansion_ids: + compute_expansion_health(expansion_id) + return len(expansion_ids) @app.task @@ -1228,6 +1256,8 @@ def readd_references_to_expansion_on_references_removal(expansion_id, removed_re if expansion and removed_reference_ids: reference_to_readd = expansion.collection_version.references.exclude(id__in=removed_reference_ids) expansion.add_references(reference_to_readd, True, True, False) + # re-adding changes members after the removal marked them, so its own recompute may have read them early + expansion.mark_health_out_of_date() current = Task.objects.filter(id=get(current_task, 'request.id')).first() if current: current.clear_superseded_readd_references_tasks() diff --git a/core/concepts/views.py b/core/concepts/views.py index 44a1fa1c5..e0540b208 100644 --- a/core/concepts/views.py +++ b/core/concepts/views.py @@ -491,6 +491,9 @@ def _db_hard_delete(self): ) parent = concept.parent + from core.collections.models import Expansion + # a raw delete takes the membership rows without the model's delete, so expansions holding them go first + Expansion.mark_health_not_current_for_members('concepts', list(concepts.values_list('id', flat=True))) result = concepts.delete() parent.update_concepts_count() return Response(result, status=status.HTTP_204_NO_CONTENT) diff --git a/core/fixtures/toggles.json b/core/fixtures/toggles.json index 0d4625d49..ca079598b 100644 --- a/core/fixtures/toggles.json +++ b/core/fixtures/toggles.json @@ -78,5 +78,17 @@ "staging": true, "production": true } + }, + { + "pk": 12, + "model": "toggles.toggle", + "fields": { + "is_active": true, + "name": "EXPANSION_HEALTH_TOGGLE", + "dev": true, + "qa": true, + "staging": true, + "production": false + } } -] \ No newline at end of file +] diff --git a/core/sources/models.py b/core/sources/models.py index a9d5a03b4..2ba69eb94 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -13,6 +13,7 @@ from django.utils import timezone from pydash import get, compact +from core.collections.constants import HEALTH_RELEVANT_VERSION_FIELDS from core.common.checksums import VersionCompareMixin from core.common.constants import HEAD, LATEST, VERSION_UNCOPYABLE_EXTRAS from core.common.fields import URIField @@ -374,6 +375,7 @@ def index_dropped_children(self, concept_ids, mapping_ids, recount=True): update_active_count(self.__class__, self.id, field) def drop_unseen_children(self, seen_concept_ids, seen_mapping_ids): + from core.collections.models import Expansion from core.mappings.models import Mapping to_index = {Concept: [], Mapping: []} with transaction.atomic(): @@ -395,6 +397,9 @@ def drop_unseen_children(self, seen_concept_ids, seen_mapping_ids): source_id=self.id, **{f'{model.__name__.lower()}_id__in': [*chunk, *latest_ids]}).delete() if model is Concept: HierarchicalConcepts.objects.filter(child_id__in=chunk).delete() + # they left HEAD, which changes their class in the expansions that hold them + Expansion.mark_health_out_of_date_for_members( + f'{model.__name__.lower()}s', [*chunk, *latest_ids]) to_index[model] += [*chunk, *latest_ids] if to_index[Concept] or to_index[Mapping]: @@ -1017,6 +1022,9 @@ def save( if self.id and 'canonical_url' in dirty_fields: self.resolve_url_registry_entries_later() + if self.id and not is_new and HEALTH_RELEVANT_VERSION_FIELDS & set(dirty_fields): + from core.collections.models import Expansion + Expansion.mark_health_not_current_for_repository(self) def __update_sequences(self, dirty_fields=[]): # pylint: disable=dangerous-default-value def should_update(is_seq, field):