Skip to content
28 changes: 25 additions & 3 deletions core/collections/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.db import models, transaction, OperationalError
from django.db.models import UniqueConstraint, F, QuerySet, Max
from django.db.models import UniqueConstraint, F, QuerySet, Max, Exists, OuterRef
from django.db.models.functions import Coalesce
from django.utils import timezone
from django.utils.functional import cached_property
Expand Down Expand Up @@ -181,6 +181,8 @@ def save(
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)
if self.id and not is_new and 'expansion_uri' in dirty_fields:
Expansion.on_default_expansion_change(self, dirty_fields['expansion_uri'])

def post_create_actions(self):
if self.should_auto_expand:
Expand Down Expand Up @@ -2654,7 +2656,8 @@ def update_health(self):
return None
from core.collections.health import ExpansionHealth
expansions = Expansion.objects.filter(id=self.id)
if not self.is_default:
# read now, not from the version a build loaded at its start: the default may have changed since
if not Collection.objects.filter(id=self.collection_version_id, expansion_uri=self.uri).exists():
expansions.update(health=None, health_is_current=None)
self.health = None
return None
Expand All @@ -2670,7 +2673,9 @@ def update_health(self):
return None
# the store bumps it too, so an older run that ends after a newer one (a rebuild's) can't overwrite it. Never
# during a build, which may have cleared the members: the build computes its own once it ends
if not expansions.filter(health_revision=revision, is_processing=False).update(
is_default = Collection.objects.filter(id=OuterRef('collection_version_id'), expansion_uri=OuterRef('uri'))
# an Exists, not a join, keeps it a one-table update that re-checks the revision of the latest committed row
if not expansions.filter(Exists(is_default), health_revision=revision, is_processing=False).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
if not expansions.filter(is_processing=True).exists():
Expand Down Expand Up @@ -2767,6 +2772,23 @@ def mark_health_not_current_for_repository(cls, repo_version):
cls.mark_health_not_current(expansion_ids)
return expansion_ids

@classmethod
def on_default_expansion_change(cls, collection_version, previous_uri):
"""Only the default keeps health: the one that stops being it drops its stored health, and the new default
is recomputed now rather than by the nightly recheck"""
expansions = cls.objects.filter(collection_version_id=collection_version.id)
if previous_uri and previous_uri != collection_version.expansion_uri:
# bumped, so a run that started while it was the default can't store its result
expansions.filter(uri=previous_uri).update(
health=None, health_is_current=None, health_revision=F('health_revision') + 1)
default = expansions.filter(uri=collection_version.expansion_uri).only('id', 'is_processing').first() \
if collection_version.expansion_uri else None
# out of date, not None: its build computes health once it ends. A build that ended meanwhile is recomputed
marked = default and default.is_processing and cls.is_health_on() and expansions.filter(
id=default.id, is_processing=True).update(health_is_current=False, health_revision=F('health_revision') + 1)
if default and not marked:
default.mark_health_out_of_date()

@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. Read from
Expand Down
124 changes: 120 additions & 4 deletions core/collections/tests/tests_health.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from datetime import timedelta

from django.db import connection
from django.db.models import F
from django.db.models.signals import pre_delete
from django.test import override_settings
from django.test.utils import CaptureQueriesContext
Expand All @@ -12,10 +11,10 @@
ExpansionHealth, RELEASE, UNRELEASED, HEAD_MEMBER, INTERIM, MISMATCH, AMBIGUOUS,
UNATTRIBUTED, EMPTY, UNHEALTHY, HEAD_RESOLVED, HEALTHY)
from core.collections.constants import EXPANSION_HEALTH_RECHECK_WINDOW_SECONDS
from core.collections.models import CollectionReference, Expansion
from core.collections.models import Collection, 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.tasks import seed_children_to_new_version, recheck_expansion_health, compute_expansion_health
from core.common.tests import OCLTestCase, OCLAPITestCase
from core.concepts.models import Concept
from core.concepts.tests.factories import ConceptFactory
Expand Down Expand Up @@ -667,12 +666,129 @@ def test_health_is_kept_for_the_default_expansion_only(self):
self.assertEqual(Expansion.objects.values_list('health', 'health_is_current').get(id=other.id), (None, None))
self.assertTrue(self.stored()[1])

def set_default(self, expansion):
collection = Collection.objects.get(id=self.collection.id)
collection.expansion_uri = expansion.uri
collection.save()

def test_a_new_default_gets_health_now_and_the_old_default_drops_its_own(self):
self.assertTrue(self.stored()[1])
new_default = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
self.assertEqual(
Expansion.objects.values_list('health', 'health_is_current').get(id=new_default.id), (None, None))

self.set_default(new_default)

health, is_current = Expansion.objects.values_list('health', 'health_is_current').get(id=new_default.id)
self.assertTrue(is_current)
self.assertEqual(health['state'], EMPTY)
self.assertEqual(self.stored(), (None, None))

def test_a_new_default_with_health_off_is_only_marked_not_current(self):
new_default = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
revision = Expansion.objects.values_list('health_revision', flat=True).get(id=new_default.id)

with patch.object(Expansion, 'is_health_on', return_value=False), \
patch.object(ExpansionHealth, 'compute') as compute:
self.set_default(new_default)

compute.assert_not_called()
self.assertGreater(
Expansion.objects.values_list('health_revision', flat=True).get(id=new_default.id), revision)
self.assertEqual(
Expansion.objects.values_list('health', 'health_is_current').get(id=new_default.id), (None, None))
self.assertEqual(self.stored(), (None, None))

def test_a_new_default_still_building_gets_health_from_its_build(self):
new_default = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
Expansion.objects.filter(id=new_default.id).update(is_processing=True)
# its build loaded the version before the switch
building = Expansion.objects.get(id=new_default.id)
self.assertFalse(building.is_default)

with patch.object(ExpansionHealth, 'compute', return_value={'state': EMPTY}) as compute:
self.set_default(new_default)
compute.assert_not_called()
Expansion.objects.filter(id=new_default.id).update(is_processing=False)
building.update_health()

self.assertEqual(
Expansion.objects.values_list('health', 'health_is_current').get(id=new_default.id),
({'state': EMPTY}, True))

def test_a_new_default_still_building_is_marked_out_of_date_until_its_build_ends(self):
new_default = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
Expansion.objects.filter(id=new_default.id).update(is_processing=True)
revision = Expansion.objects.values_list('health_revision', flat=True).get(id=new_default.id)

with patch.object(ExpansionHealth, 'compute') as compute:
self.set_default(new_default)

compute.assert_not_called()
health_revision, health, is_current = Expansion.objects.values_list(
'health_revision', 'health', 'health_is_current').get(id=new_default.id)
self.assertGreater(health_revision, revision)
self.assertEqual((health, is_current), (None, False))

def test_a_new_default_still_building_with_health_off_is_only_marked_not_current(self):
new_default = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
Expansion.objects.filter(id=new_default.id).update(is_processing=True)

with patch.object(Expansion, 'is_health_on', return_value=False):
self.set_default(new_default)

self.assertIsNone(Expansion.objects.values_list('health_is_current', flat=True).get(id=new_default.id))

def test_a_new_default_whose_build_ends_while_it_is_marked_is_recomputed(self):
new_default = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
Expansion.objects.filter(id=new_default.id).update(is_processing=True)

def build_ends():
Expansion.objects.filter(id=new_default.id).update(is_processing=False)
return True

with patch.object(Expansion, 'is_health_on', side_effect=build_ends), \
patch.object(Expansion, 'mark_health_out_of_date') as mark_health_out_of_date:
self.set_default(new_default)

mark_health_out_of_date.assert_called_once()

def test_the_store_is_a_one_table_update(self):
with CaptureQueriesContext(connection) as context:
self.expansion.update_health()

stores = [query['sql'] for query in context.captured_queries
if query['sql'].startswith('UPDATE "collection_expansions"') and '"health_is_current" = true' in
query['sql']]
self.assertEqual(len(stores), 1, stores)
self.assertNotIn('IN (SELECT', stores[0])
self.assertIn('EXISTS', stores[0])
self.assertTrue(self.stored()[1])

def test_a_build_of_the_old_default_ending_after_the_switch_stores_no_health(self):
new_default = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
rebuilding = Expansion.objects.get(id=self.expansion.id)
self.assertTrue(rebuilding.is_default)

self.set_default(new_default)
rebuilding.update_health()

self.assertEqual(self.stored(), (None, None))

def test_a_queued_run_skips_health_a_newer_run_already_stored(self):
self.assertTrue(self.stored()[1])

with patch.object(ExpansionHealth, 'compute') as compute:
compute_expansion_health(self.expansion.id)

compute.assert_not_called()

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)
Expansion.mark_health_not_current([self.expansion.id])
computed.append(1)
return {'state': HEALTHY, 'run': len(computed)}

Expand Down
3 changes: 2 additions & 1 deletion core/common/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,8 @@ def seed_children_to_expansion(expansion_id, index=True, force_reevaluate=False)
def compute_expansion_health(expansion_id):
from core.collections.models import Expansion
expansion = Expansion.objects.filter(id=expansion_id).first()
if expansion:
# current: a run that read the change, a build's own, stored it after this was queued
if expansion and expansion.health_is_current is not True:
expansion.update_health()


Expand Down
Loading