From 619f921c9f3ac878e7ad3440d1622debd43c70b6 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Mon, 23 Nov 2026 08:55:05 +0530 Subject: [PATCH 1/6] OpenConceptLab/ocl_issues#3003 | expansion health stored on the expansion, computed at build, rebuild and copy, recomputed after reference changes --- core/collections/constants.py | 2 + .../migrations/0074_expansion_health.py | 21 +++++ core/collections/models.py | 76 ++++++++++++++-- core/collections/tests/tests_health.py | 91 +++++++++++++++++++ core/common/tasks.py | 11 +++ core/fixtures/toggles.json | 14 ++- 6 files changed, 207 insertions(+), 8 deletions(-) create mode 100644 core/collections/migrations/0074_expansion_health.py diff --git a/core/collections/constants.py b/core/collections/constants.py index 820427a3e..4ce1c5ff8 100644 --- a/core/collections/constants.py +++ b/core/collections/constants.py @@ -48,6 +48,8 @@ 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 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..8c210fd1b --- /dev/null +++ b/core/collections/migrations/0074_expansion_health.py @@ -0,0 +1,21 @@ +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), + ), + ] diff --git a/core/collections/models.py b/core/collections/models.py index b5ff15c24..859bc2777 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) from core.collections.parsers import CollectionReferenceParser from core.collections.translators import CollectionReferenceTranslator from core.collections.utils import is_concept, is_mapping @@ -33,7 +35,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, \ @@ -48,6 +50,7 @@ TRUTHY = get_truthy_values() FALSEY = get_falsy_values() +logger = logging.getLogger('oclapi') class Collection(DirtyFieldsMixin, VersionCompareMixin, ConceptContainerModel): @@ -299,7 +302,10 @@ 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() self.__dict__.pop('locked_source_versions', None) self.__dict__.pop('locked_collection_versions', None) if user and user.is_authenticated: @@ -329,9 +335,12 @@ 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() return self.remove_references(self.references.filter(expression__in=expressions)) @@ -339,9 +348,12 @@ 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() def get_cascaded_mapping_uris_from_concept_expressions(self, expressions): mapping_uris = [] @@ -425,6 +437,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)), @@ -1587,6 +1600,10 @@ 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) + HEALTH_FIELDS = ('health', 'health_is_current') @property def is_head(self): @@ -2475,6 +2492,51 @@ 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. 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 + # current from here: a change while it computes marks it out of date again and queues another run + Expansion.objects.filter(id=self.id).update(health_is_current=True) + try: + health = ExpansionHealth(self).compute() + except Exception: # pylint: disable=broad-except + logger.exception('Expansion health failed for %s', self.uri) + Expansion.objects.filter(id=self.id).update(health_is_current=False) + return None + Expansion.objects.filter(id=self.id).update(health=health) + self.health = health + return health + + def mark_health_out_of_date(self): + """Marks the health out of date and queues one recompute, however many changes follow before it runs""" + if not self.is_health_on(): + return + self.health_is_current = False + if not Expansion.objects.filter(id=self.id).exclude(health_is_current=False).update(health_is_current=False): + return # already out of date, so a recompute is queued + if get(settings, 'TEST_MODE', False): + compute_expansion_health(self.id) + else: + expansion_id = self.id + transaction.on_commit(lambda: compute_expansion_health.apply_async( + (expansion_id,), queue='default', countdown=EXPANSION_HEALTH_DEBOUNCE_SECONDS)) + def clear_processing(self, full_save=False): if self.is_processing: self.is_processing = False diff --git a/core/collections/tests/tests_health.py b/core/collections/tests/tests_health.py index 1b7ebe74d..1c6075069 100644 --- a/core/collections/tests/tests_health.py +++ b/core/collections/tests/tests_health.py @@ -7,6 +7,7 @@ UNATTRIBUTED, EMPTY, UNHEALTHY, HEAD_RESOLVED, HEALTHY) from core.collections.models import CollectionReference, Expansion from core.collections.tests.factories import OrganizationCollectionFactory, ExpansionFactory +from core.common.tasks import seed_children_to_new_version from core.common.tests import OCLTestCase from core.concepts.tests.factories import ConceptFactory from core.mappings.tests.factories import MappingFactory @@ -338,3 +339,93 @@ def count_queries(references_count): return len(context.captured_queries) self.assertEqual(count_queries(2), count_queries(6)) + + +class ExpansionHealthStorageTest(OCLTestCase): + 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() + + 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_writes_no_health(self): + with patch.object(Expansion, 'is_health_on', return_value=False): + expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + self.add(ConceptFactory()) + + self.assertEqual( + Expansion.objects.values_list('health', 'health_is_current').get(id=expansion.id), (None, None)) + + def test_a_failure_leaves_health_out_of_date_and_the_build_done(self): + with patch.object(ExpansionHealth, 'compute', side_effect=ValueError('boom')): + expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + + expansion.refresh_from_db() + self.assertFalse(expansion.is_processing) + self.assertEqual((expansion.health, expansion.health_is_current), (None, False)) + + 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/tasks.py b/core/common/tasks.py index 623dd3b9c..d3564f28a 100644 --- a/core/common/tasks.py +++ b/core/common/tasks.py @@ -493,6 +493,15 @@ 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 @@ -1171,6 +1180,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/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 +] From 30dade1442602d7a23752d9577217a5215d309ae Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Mon, 23 Nov 2026 09:05:09 +0530 Subject: [PATCH 2/6] OpenConceptLab/ocl_issues#3003 | a failed health compute is recomputed on the next change; releasing, retiring or deleting a repo version leaves dependent expansions not current --- core/collections/constants.py | 2 + core/collections/models.py | 22 +++++++++- core/collections/tests/tests_health.py | 57 +++++++++++++++++++++++++- core/common/models.py | 3 ++ core/sources/models.py | 4 ++ 5 files changed, 84 insertions(+), 4 deletions(-) diff --git a/core/collections/constants.py b/core/collections/constants.py index 4ce1c5ff8..5556427e8 100644 --- a/core/collections/constants.py +++ b/core/collections/constants.py @@ -50,6 +50,8 @@ 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'} VERSION_EXPANSION_LOCK = 'lock' VERSION_EXPANSION_LATEST = 'latest' VERSION_EXPANSION_NONE = 'none' diff --git a/core/collections/models.py b/core/collections/models.py index 859bc2777..4991a5dc8 100644 --- a/core/collections/models.py +++ b/core/collections/models.py @@ -21,7 +21,7 @@ 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, - EXPANSION_HEALTH_TOGGLE, EXPANSION_HEALTH_DEBOUNCE_SECONDS) + 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 @@ -172,6 +172,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, @@ -179,6 +180,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: @@ -2517,12 +2520,27 @@ def update_health(self): health = ExpansionHealth(self).compute() except Exception: # pylint: disable=broad-except logger.exception('Expansion health failed for %s', self.uri) - Expansion.objects.filter(id=self.id).update(health_is_current=False) + # None, not False: nothing is queued, so the next change queues a recompute + Expansion.objects.filter(id=self.id).update(health_is_current=None) return None Expansion.objects.filter(id=self.id).update(health=health) self.health = health return health + @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 or delete leaves them not current. One update, no task: their next change recomputes them""" + if not cls.is_health_on(): + return + kind = 'collection' if isinstance(repo_version, Collection) else 'source' + version_ids = repo_version.versions.values('id') + cls.objects.filter( + models.Q(**{f'explicit_{kind}_versions__in': version_ids}) | + models.Q(**{f'evaluated_{kind}_versions__in': version_ids}), + health_is_current=True + ).update(health_is_current=None) + def mark_health_out_of_date(self): """Marks the health out of date and queues one recompute, however many changes follow before it runs""" if not self.is_health_on(): diff --git a/core/collections/tests/tests_health.py b/core/collections/tests/tests_health.py index 1c6075069..9097f7dbc 100644 --- a/core/collections/tests/tests_health.py +++ b/core/collections/tests/tests_health.py @@ -1,6 +1,6 @@ from django.db import connection 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, RESOURCE_VERSIONED, INTERIM, MISMATCH, AMBIGUOUS, @@ -408,7 +408,60 @@ def test_a_failure_leaves_health_out_of_date_and_the_build_done(self): expansion.refresh_from_db() self.assertFalse(expansion.is_processing) - self.assertEqual((expansion.health, expansion.health_is_current), (None, False)) + self.assertEqual((expansion.health, expansion.health_is_current), (None, 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) + other = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + 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_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]) def test_a_save_from_an_older_copy_keeps_the_health(self): older = Expansion.objects.get(id=self.expansion.id) diff --git a/core/common/models.py b/core/common/models.py index 8d80824c0..5c4c86696 100644 --- a/core/common/models.py +++ b/core/common/models.py @@ -982,6 +982,9 @@ 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 + Expansion.mark_health_not_current_for_repository(self) export_paths = self.get_export_paths_to_delete() deleted_urls = [self.url] deleted_ids = [self.id] diff --git a/core/sources/models.py b/core/sources/models.py index 07c0764a2..b609e1c20 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, VERSION_UNCOPYABLE_EXTRAS from core.common.fields import URIField @@ -945,6 +946,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): From b427f19611fe792b503443c6b86e9768eb44ef9b Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Mon, 23 Nov 2026 10:14:47 +0530 Subject: [PATCH 3/6] OpenConceptLab/ocl_issues#3003 | removal tests that count the re-add's callbacks and tasks run with expansion health off --- core/collections/tests/tests.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/collections/tests/tests.py b/core/collections/tests/tests.py index e5b885be6..badb52e21 100644 --- a/core/collections/tests/tests.py +++ b/core/collections/tests/tests.py @@ -2575,6 +2575,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') @@ -2760,6 +2761,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') @@ -2798,6 +2800,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') @@ -2819,6 +2822,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') From f63ff3054b6574d070b1e90c26d234ba0431e55b Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Tue, 24 Nov 2026 08:56:04 +0530 Subject: [PATCH 4/6] OpenConceptLab/ocl_issues#3003 | health is kept for default expansions, stored as current only if unchanged while computing, marked on HEAD edits, deletes and value-set changes, and rechecked nightly --- core/celery.py | 4 + core/collections/constants.py | 3 +- .../migrations/0074_expansion_health.py | 5 + core/collections/models.py | 119 ++++++++++++---- core/collections/tests/tests_health.py | 128 ++++++++++++++++-- core/common/mixins.py | 17 +++ core/common/models.py | 6 +- core/common/tasks.py | 18 +++ core/concepts/views.py | 3 + 9 files changed, 267 insertions(+), 36 deletions(-) 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 5556427e8..585043ce6 100644 --- a/core/collections/constants.py +++ b/core/collections/constants.py @@ -51,7 +51,8 @@ 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'} +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 index 8c210fd1b..d8e9807d9 100644 --- a/core/collections/migrations/0074_expansion_health.py +++ b/core/collections/migrations/0074_expansion_health.py @@ -18,4 +18,9 @@ class Migration(migrations.Migration): 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 0333c4268..f8e24b77a 100644 --- a/core/collections/models.py +++ b/core/collections/models.py @@ -307,6 +307,8 @@ def add_references(self, references, user=None, _async=False): 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: @@ -343,6 +345,7 @@ def delete_references(self, 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)) @@ -356,6 +359,7 @@ def remove_references(self, 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 = [] @@ -1636,7 +1640,9 @@ class Meta: # 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) - HEALTH_FIELDS = ('health', 'health_is_current') + # 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): @@ -2555,51 +2561,118 @@ def is_health_on(): return bool(Toggle.get(EXPANSION_HEALTH_TOGGLE)) def update_health(self): - """Computes and saves the health summary. A failure is logged and leaves it out of date; it never fails - the build that called it""" + """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 - # current from here: a change while it computes marks it out of date again and queues another run - Expansion.objects.filter(id=self.id).update(health_is_current=True) + 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 - Expansion.objects.filter(id=self.id).update(health_is_current=None) + expansions.filter(health_revision=revision).update(health_is_current=None) + return None + if not expansions.filter(health_revision=revision).update(health=health, health_is_current=True): + # marked while it computed: a fresh run reads the change + self.queue_health_recompute(self.id) return None - Expansion.objects.filter(id=self.id).update(health=health) 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 or delete leaves them not current. One update, no task: their next change recomputes them""" - if not cls.is_health_on(): - return + 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') - cls.objects.filter( + expansion_ids = list(cls.objects.filter( models.Q(**{f'explicit_{kind}_versions__in': version_ids}) | - models.Q(**{f'evaluated_{kind}_versions__in': version_ids}), - health_is_current=True - ).update(health_is_current=None) + 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""" + 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 cls.is_health_on(): + cls.mark_health_not_current(expansion_ids) + return + for expansion in cls.objects.filter(id__in=expansion_ids): + expansion.mark_health_out_of_date() def mark_health_out_of_date(self): - """Marks the health out of date and queues one recompute, however many changes follow before it runs""" + """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 - if not Expansion.objects.filter(id=self.id).exclude(health_is_current=False).update(health_is_current=False): - return # already out of date, so a recompute is queued - if get(settings, 'TEST_MODE', False): - compute_expansion_health(self.id) - else: - expansion_id = self.id - transaction.on_commit(lambda: compute_expansion_health.apply_async( - (expansion_id,), queue='default', countdown=EXPANSION_HEALTH_DEBOUNCE_SECONDS)) + if not expansions.exclude(health_is_current=False).update(health_is_current=False, health_revision=bump): + # already out of date: its queued run reads this change too + expansions.update(health_revision=bump) + return + self.queue_health_recompute(self.id) def clear_processing(self, full_save=False): if self.is_processing: diff --git a/core/collections/tests/tests_health.py b/core/collections/tests/tests_health.py index f9fed8507..0e1378c87 100644 --- a/core/collections/tests/tests_health.py +++ b/core/collections/tests/tests_health.py @@ -1,4 +1,6 @@ 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, Mock @@ -8,7 +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 +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 @@ -580,21 +582,55 @@ def test_an_expansion_already_out_of_date_queues_no_second_recompute(self): compute.assert_not_called() self.assertFalse(self.stored()[1]) - def test_toggle_off_writes_no_health(self): - with patch.object(Expansion, 'is_health_on', return_value=False): - expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + 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()) - self.assertEqual( - Expansion.objects.values_list('health', 'health_is_current').get(id=expansion.id), (None, None)) + # 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')): - expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + self.expansion.seed_children(index=False) + self.expansion.update_health() - expansion.refresh_from_db() + expansion = Expansion.objects.get(id=self.expansion.id) self.assertFalse(expansion.is_processing) - self.assertEqual((expansion.health, expansion.health_is_current), (None, None)) + 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')): @@ -613,7 +649,12 @@ def recorded_source_version(self, **kwargs): mnemonic=source.mnemonic, organization=source.organization, version='v1', is_latest_version=False, **kwargs) self.expansion.evaluated_source_versions.add(source) - other = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + # 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): @@ -633,6 +674,14 @@ def test_retiring_a_version_of_a_recorded_repository_leaves_health_not_current(s 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) @@ -649,6 +698,65 @@ def test_deleting_a_version_of_a_recorded_repository_leaves_health_not_current(s 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() + self.add(concept) + self.assertEqual(self.stored()[0]['state'], HEAD_RESOLVED) + member = concept.get_latest_version() + + # 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_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_leaves_queued_ones_to_their_run(self): + Expansion.objects.filter(id=self.expansion.id).update(health_is_current=False) + + self.assertEqual(recheck_expansion_health(), 0) + 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) 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 4c298cbf3..e9221dd4f 100644 --- a/core/common/models.py +++ b/core/common/models.py @@ -982,8 +982,9 @@ def versions(self): 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 - Expansion.mark_health_not_current_for_repository(self) + # 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] @@ -1014,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 460642f45..22a8a737f 100644 --- a/core/common/tasks.py +++ b/core/common/tasks.py @@ -513,6 +513,24 @@ def compute_expansion_health(expansion_id): 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 and has no run + queued. A release, retire or delete leaves them so, and a frozen release never gets another change""" + 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.filter( + health_is_current__isnull=True, 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 def update_validation_schema(instance_type, instance_id, target_schema): klass = get_resource_class_from_resource_name(instance_type) 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) From 3cacf5be25e26f03f2ed9590f13e06cfad6df613 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Tue, 24 Nov 2026 09:47:19 +0530 Subject: [PATCH 5/6] OpenConceptLab/ocl_issues#3003 | A seed that ends before its expansion is the version's default still stores health, and the storage tests claim the default before seeding --- core/collections/models.py | 3 +++ core/collections/tests/tests_health.py | 19 ++++++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/core/collections/models.py b/core/collections/models.py index f8e24b77a..53e2fdb94 100644 --- a/core/collections/models.py +++ b/core/collections/models.py @@ -399,6 +399,9 @@ 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(): + expansion.update_health() return expansion diff --git a/core/collections/tests/tests_health.py b/core/collections/tests/tests_health.py index 0e1378c87..f211ce4e7 100644 --- a/core/collections/tests/tests_health.py +++ b/core/collections/tests/tests_health.py @@ -533,9 +533,10 @@ class ExpansionHealthStorageTest(OCLTestCase): 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() + # 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( @@ -723,9 +724,10 @@ def test_a_change_to_a_value_set_leaves_expansions_judged_against_it_not_current def test_editing_a_member_in_head_recomputes_the_expansions_holding_it(self): concept = ConceptFactory() - self.add(concept) - self.assertEqual(self.stored()[0]['state'], HEAD_RESOLVED) 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() @@ -734,6 +736,13 @@ def test_editing_a_member_in_head_recomputes_the_expansions_holding_it(self): 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() + with patch.object(CollectionReference, 'is_expansion_locked_repo_version_on', return_value=False): + collection.cascade_children_to_expansion(index=False) + + self.assertTrue(collection.expansion.health_is_current) + def test_a_hard_deleted_member_leaves_the_expansions_holding_it_not_current(self): concept = ConceptFactory() self.add(concept) From 5b93c92138835cb126d9ab29a50e553f6ec6c7ac Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Tue, 24 Nov 2026 11:56:51 +0530 Subject: [PATCH 6/6] OpenConceptLab/ocl_issues#3003 | A mark bumps the revision before flipping and a store bumps it too, the nightly recheck takes rows left out of date, and dropped HEAD children mark their expansions --- core/collections/models.py | 30 +++++++++---- core/collections/tests/tests_health.py | 58 ++++++++++++++++++++++++-- core/common/tasks.py | 9 ++-- core/sources/models.py | 4 ++ 4 files changed, 85 insertions(+), 16 deletions(-) diff --git a/core/collections/models.py b/core/collections/models.py index 53e2fdb94..c8759f3f4 100644 --- a/core/collections/models.py +++ b/core/collections/models.py @@ -401,6 +401,8 @@ def cascade_children_to_expansion(self, expansion_data=None, index=True, sync=Fa 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 @@ -2585,8 +2587,10 @@ def update_health(self): # 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 - if not expansions.filter(health_revision=revision).update(health=health, health_is_current=True): - # marked while it computed: a fresh run reads the change + # 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 @@ -2652,14 +2656,23 @@ def mark_health_not_current_for_members(cls, resource_type, member_ids): 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 - for expansion in cls.objects.filter(id__in=expansion_ids): - expansion.mark_health_out_of_date() + 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 @@ -2671,11 +2684,10 @@ def mark_health_out_of_date(self): self.health_is_current = None return self.health_is_current = False - if not expansions.exclude(health_is_current=False).update(health_is_current=False, health_revision=bump): - # already out of date: its queued run reads this change too - expansions.update(health_revision=bump) - return - self.queue_health_recompute(self.id) + # 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: diff --git a/core/collections/tests/tests_health.py b/core/collections/tests/tests_health.py index 5298c05ae..d6562a7aa 100644 --- a/core/collections/tests/tests_health.py +++ b/core/collections/tests/tests_health.py @@ -739,10 +739,30 @@ def test_editing_a_member_in_head_recomputes_the_expansions_holding_it(self): 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) - self.assertTrue(collection.expansion.health_is_current) + 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() @@ -762,10 +782,42 @@ def test_the_nightly_recheck_recomputes_default_expansions_that_are_not_current( 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_leaves_queued_ones_to_their_run(self): + 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(), 0) + 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) diff --git a/core/common/tasks.py b/core/common/tasks.py index 22a8a737f..ee4fb9e2d 100644 --- a/core/common/tasks.py +++ b/core/common/tasks.py @@ -515,15 +515,16 @@ def compute_expansion_health(expansion_id): @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 and has no run - queued. A release, retire or delete leaves them so, and a frozen release never gets another change""" + """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.filter( - health_is_current__isnull=True, is_processing=False, is_active=True, collection_version__is_active=True, + 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: diff --git a/core/sources/models.py b/core/sources/models.py index 62f971f56..2ba69eb94 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -375,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(): @@ -396,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]: