From 64e8a65e1a294415384b2687e8571c8d1dcbf6a4 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Mon, 23 Nov 2026 13:14:44 +0530 Subject: [PATCH 1/6] OpenConceptLab/ocl_issues#3003 | backfill_expansion_health computes health for expansions that need it, dry run by default --- .../tests/tests_health_backfill.py | 136 ++++++++++++++++++ .../commands/backfill_expansion_health.py | 115 +++++++++++++++ 2 files changed, 251 insertions(+) create mode 100644 core/collections/tests/tests_health_backfill.py create mode 100644 core/common/management/commands/backfill_expansion_health.py diff --git a/core/collections/tests/tests_health_backfill.py b/core/collections/tests/tests_health_backfill.py new file mode 100644 index 000000000..8a396cf92 --- /dev/null +++ b/core/collections/tests/tests_health_backfill.py @@ -0,0 +1,136 @@ +import json +import os +import tempfile +from io import StringIO + +from django.core.management import call_command, CommandError +from mock import patch + +from core.collections.health import EMPTY, RULES_VERSION, ExpansionHealth +from core.collections.models import Expansion +from core.collections.tests.factories import OrganizationCollectionFactory +from core.common.tests import OCLTestCase + + +class ExpansionHealthBackfillTest(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() + self.clear(self.expansion) + + @staticmethod + def clear(expansion, **kwargs): + Expansion.objects.filter(id=expansion.id).update(**{'health': None, 'health_is_current': None, **kwargs}) + + @staticmethod + def stored(expansion): + return Expansion.objects.values_list('health', 'health_is_current').get(id=expansion.id) + + def another_expansion(self): + collection = OrganizationCollectionFactory() + expansion = Expansion.persist(index=False, collection_version=collection, mnemonic='autoexpand-HEAD') + collection.expansion_uri = expansion.uri + collection.save() + return expansion + + def run_command(self, *args, **kwargs): + out = StringIO() + call_command('backfill_expansion_health', *args, stdout=out, **kwargs) + return out.getvalue() + + def test_dry_run_computes_and_stores_nothing(self): + out = self.run_command(self.expansion.uri) + + self.assertIn('DRY RUN. Rules version', out) + self.assertIn(f'{self.expansion.uri}: None -> {EMPTY}', out) + self.assertIn('"expansions": 1', out) + self.assertEqual(self.stored(self.expansion), (None, None)) + + def test_apply_stores_current_health(self): + self.run_command(self.expansion.uri, apply=True) + + health, is_current = self.stored(self.expansion) + self.assertTrue(is_current) + self.assertEqual(health['state'], EMPTY) + self.assertEqual(health['rules_version'], RULES_VERSION) + + def test_apply_needs_the_toggle_on(self): + with patch.object(Expansion, 'is_health_on', return_value=False): + with self.assertRaises(CommandError): + self.run_command(self.expansion.uri, apply=True) + + self.assertEqual(self.stored(self.expansion), (None, None)) + + def test_all_takes_only_expansions_that_need_it(self): + current = self.another_expansion() + not_current = self.another_expansion() + older_rules = self.another_expansion() + Expansion.objects.filter(id=not_current.id).update(health_is_current=False) + Expansion.objects.filter(id=older_rules.id).update(health={'state': EMPTY, 'rules_version': 0}) + + out = self.run_command(all=True) + + self.assertIn(self.expansion.uri, out) + self.assertIn(not_current.uri, out) + self.assertIn(older_rules.uri, out) + self.assertNotIn(f'{current.uri}:', out) + + self.assertIn(f'{current.uri}:', self.run_command(all=True, force=True)) + + def test_all_skips_expansions_being_built(self): + Expansion.objects.filter(id=self.expansion.id).update(is_processing=True) + + self.assertNotIn(f'{self.expansion.uri}:', self.run_command(all=True)) + + def test_all_resumes_after_an_id_and_stops_at_the_limit(self): + second = self.another_expansion() + third = self.another_expansion() + self.clear(second) + self.clear(third) + + out = self.run_command(all=True, start_after_id=self.expansion.id, limit=1) + + self.assertNotIn(f'{self.expansion.uri}:', out) + self.assertIn(f'{second.uri}:', out) + self.assertNotIn(f'{third.uri}:', out) + + def test_collection_version_uri_takes_its_default_expansion(self): + self.assertIn(f'{self.expansion.uri}:', self.run_command(self.collection.uri)) + + def test_a_failure_is_reported_and_the_run_goes_on(self): + other = self.another_expansion() + results = [ValueError('boom'), {'state': EMPTY, 'reasons': []}] + with patch.object(ExpansionHealth, 'compute', side_effect=results): + out = self.run_command(self.expansion.uri, other.uri) + + self.assertIn(f'FAILED {self.expansion.uri}: ValueError: boom', out) + self.assertIn(f'{other.uri}: ', out) + self.assertIn('"failed": 1', out) + + def test_a_failure_while_applying_leaves_health_not_current(self): + with patch.object(ExpansionHealth, 'compute', side_effect=ValueError('boom')): + out = self.run_command(self.expansion.uri, apply=True) + + self.assertIn(f'FAILED {self.expansion.uri}: computing health failed', out) + self.assertEqual(self.stored(self.expansion), (None, None)) + + def test_output_has_a_line_per_expansion(self): + with tempfile.TemporaryDirectory() as directory: + output = os.path.join(directory, 'report.jsonl') + self.run_command(self.expansion.uri, output=output) + with open(output, encoding='utf-8') as file: + reports = [json.loads(line) for line in file] + + self.assertEqual(len(reports), 1) + self.assertEqual(reports[0]['before'], {'state': None, 'is_current': None, 'rules_version': None}) + self.assertEqual(reports[0]['health']['state'], EMPTY) + self.assertTrue(reports[0]['is_default']) + + def test_needs_uris_or_all(self): + with self.assertRaises(CommandError): + self.run_command() + with self.assertRaises(CommandError): + self.run_command(self.expansion.uri, all=True) diff --git a/core/common/management/commands/backfill_expansion_health.py b/core/common/management/commands/backfill_expansion_health.py new file mode 100644 index 000000000..d3b9f0433 --- /dev/null +++ b/core/common/management/commands/backfill_expansion_health.py @@ -0,0 +1,115 @@ +import json +import time +from collections import Counter + +from django.core.management import BaseCommand, CommandError +from django.db.models import Q + +from core.collections.constants import EXPANSION_HEALTH_TOGGLE +from core.collections.health import RULES_VERSION, ExpansionHealth +from core.collections.models import Collection, Expansion + + +class Command(BaseCommand): + help = ('Computes expansion health for expansions that have none, or whose health is not current or was computed ' + 'with older rules. A dry run unless --apply is given: it computes and reports, and stores nothing. ' + 'Run it after rebuild_expansion_version_lists, whose lists health reads.') + + def add_arguments(self, parser): + parser.add_argument( + 'uris', nargs='*', help='Expansion URIs, or collection version URIs for their default expansion') + parser.add_argument('--all', action='store_true', help='Every active expansion that needs it, by id') + parser.add_argument('--apply', action='store_true', help='Store the computed health; without it, a dry run') + parser.add_argument( + '--force', action='store_true', help='--all: also expansions whose health is current and up to date') + parser.add_argument('--start-after-id', type=int, default=0, help='--all: resume after this expansion id') + parser.add_argument('--limit', type=int, help='--all: stop after this many expansions') + parser.add_argument('--pause', type=float, default=0, help='Seconds to wait between expansions') + parser.add_argument('--output', help='Append each expansion\'s result, and each failure, as JSON lines') + + def handle(self, *args, **options): + if bool(options['uris']) == options['all']: + raise CommandError('Pass expansion or collection version URIs, or --all') + if options['apply'] and not Expansion.is_health_on(): + raise CommandError( + f'{EXPANSION_HEALTH_TOGGLE} is off here, so stored health would not be kept current. Turn it on first') + self.options = options + self.totals = Counter() + self.states = Counter() + self.reasons = Counter() + mode = 'APPLY' if options['apply'] else 'DRY RUN' + self.stdout.write(f'{mode}. Rules version {RULES_VERSION}.') + for index, expansion_id in enumerate(self.get_expansion_ids()): + if index and options['pause']: + time.sleep(options['pause']) + self.backfill(expansion_id) + totals = {**self.totals, 'states': dict(self.states), 'reasons': dict(self.reasons)} + self.stdout.write(f'{mode} done: {json.dumps(totals, sort_keys=True)}') + if options['output']: + self.stdout.write(f'Full report: {options["output"]}') + + def get_expansion_ids(self): + if not self.options['all']: + return [self.get_expansion(uri).id for uri in self.options['uris']] + expansions = Expansion.objects.filter( + is_active=True, collection_version__is_active=True, is_processing=False, + id__gt=self.options['start_after_id']) + if not self.options['force']: + # none yet, not current, or computed with older rules + expansions = expansions.filter( + Q(health__isnull=True) | ~Q(health_is_current=True) | ~Q(health__rules_version=RULES_VERSION)) + ids = expansions.order_by('id').values_list('id', flat=True) + return list(ids[:self.options['limit']] if self.options['limit'] else ids) + + @staticmethod + def get_expansion(uri): + expansion = Expansion.objects.filter(uri=uri).first() + if not expansion: + version = Collection.objects.filter(uri=uri).first() + expansion = version.expansion if version else None + if not expansion: + raise CommandError(f'No expansion for {uri}') + return expansion + + def backfill(self, expansion_id): + expansion = Expansion.objects.filter(id=expansion_id).select_related('collection_version').first() + if not expansion: + return + before = {'state': (expansion.health or {}).get('state'), 'is_current': expansion.health_is_current, + 'rules_version': (expansion.health or {}).get('rules_version')} + started = time.time() + try: + health = expansion.update_health() if self.options['apply'] else ExpansionHealth(expansion).compute() + except Exception as ex: # pylint: disable=broad-except + health, error = None, f'{type(ex).__name__}: {ex}' + else: + error = None if health else 'computing health failed; see the log' + report = { + 'expansion': expansion.uri, + 'id': expansion.id, + 'collection_version': expansion.collection_version.uri, + 'is_default': expansion.collection_version.expansion_uri == expansion.uri, + 'before': before, + 'seconds': round(time.time() - started, 2), + } + if error: + self.totals['failed'] += 1 + self.write({**report, 'error': error}) + return + self.totals['expansions'] += 1 + self.states[health['state']] += 1 + for reason in health['reasons']: + self.reasons[reason['code']] += 1 + self.write({**report, 'health': health}) + + def write(self, report): + if 'error' in report: + self.stdout.write(f'FAILED {report["expansion"]}: {report["error"]}') + else: + health = report['health'] + reasons = ' '.join(sorted(reason['code'] for reason in health['reasons'])) + self.stdout.write( + f'{report["expansion"]}: {report["before"]["state"]} -> {health["state"]} {reasons}'.rstrip()) + if self.options['output']: + with open(self.options['output'], 'a', encoding='utf-8') as file: + file.write(json.dumps(report, default=str) + '\n') From 19928353af0914cdbf0ba7ddc65d48c1637bfd13 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Mon, 23 Nov 2026 13:18:54 +0530 Subject: [PATCH 2/6] OpenConceptLab/ocl_issues#3003 | the backfill skips and reports expansions being built, and ones a build made current since the run listed them --- .../tests/tests_health_backfill.py | 27 +++++++++++++++++-- .../commands/backfill_expansion_health.py | 24 ++++++++++++++--- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/core/collections/tests/tests_health_backfill.py b/core/collections/tests/tests_health_backfill.py index 8a396cf92..5b03a6753 100644 --- a/core/collections/tests/tests_health_backfill.py +++ b/core/collections/tests/tests_health_backfill.py @@ -9,6 +9,7 @@ from core.collections.health import EMPTY, RULES_VERSION, ExpansionHealth from core.collections.models import Expansion from core.collections.tests.factories import OrganizationCollectionFactory +from core.common.management.commands.backfill_expansion_health import Command from core.common.tests import OCLTestCase @@ -80,10 +81,32 @@ def test_all_takes_only_expansions_that_need_it(self): self.assertIn(f'{current.uri}:', self.run_command(all=True, force=True)) - def test_all_skips_expansions_being_built(self): + def test_all_skips_and_reports_expansions_being_built(self): Expansion.objects.filter(id=self.expansion.id).update(is_processing=True) - self.assertNotIn(f'{self.expansion.uri}:', self.run_command(all=True)) + out = self.run_command(all=True, apply=True) + + self.assertIn(f'SKIPPED {self.expansion.uri}: being built', out) + self.assertIn('"skipped_being_built": 1', out) + self.assertEqual(self.stored(self.expansion), (None, None)) + + def test_a_uri_being_built_is_skipped_too(self): + Expansion.objects.filter(id=self.expansion.id).update(is_processing=True) + + out = self.run_command(self.expansion.uri, apply=True) + + self.assertIn(f'SKIPPED {self.expansion.uri}: being built', out) + self.assertEqual(self.stored(self.expansion), (None, None)) + + def test_all_skips_an_expansion_a_build_made_current_since_the_run_listed_it(self): + current = self.another_expansion() + with patch.object(Command, 'get_expansion_ids', return_value=[current.id]), \ + patch.object(ExpansionHealth, 'compute') as compute: + out = self.run_command(all=True) + + compute.assert_not_called() + self.assertIn(f'SKIPPED {current.uri}: now current', out) + self.assertIn('"skipped_now_current": 1', out) def test_all_resumes_after_an_id_and_stops_at_the_limit(self): second = self.another_expansion() diff --git a/core/common/management/commands/backfill_expansion_health.py b/core/common/management/commands/backfill_expansion_health.py index d3b9f0433..19b1d62f9 100644 --- a/core/common/management/commands/backfill_expansion_health.py +++ b/core/common/management/commands/backfill_expansion_health.py @@ -13,6 +13,7 @@ class Command(BaseCommand): help = ('Computes expansion health for expansions that have none, or whose health is not current or was computed ' 'with older rules. A dry run unless --apply is given: it computes and reports, and stores nothing. ' + 'Expansions being built are skipped and reported, since their build stores health when it ends. ' 'Run it after rebuild_expansion_version_lists, whose lists health reads.') def add_arguments(self, parser): @@ -51,9 +52,9 @@ def handle(self, *args, **options): def get_expansion_ids(self): if not self.options['all']: return [self.get_expansion(uri).id for uri in self.options['uris']] + # those being built are listed too, so a skipped one shows in the report expansions = Expansion.objects.filter( - is_active=True, collection_version__is_active=True, is_processing=False, - id__gt=self.options['start_after_id']) + is_active=True, collection_version__is_active=True, id__gt=self.options['start_after_id']) if not self.options['force']: # none yet, not current, or computed with older rules expansions = expansions.filter( @@ -75,6 +76,11 @@ def backfill(self, expansion_id): expansion = Expansion.objects.filter(id=expansion_id).select_related('collection_version').first() if not expansion: return + skipped = self.get_skip_reason(expansion) + if skipped: + self.totals[f'skipped_{skipped.replace(" ", "_")}'] += 1 + self.write({'expansion': expansion.uri, 'id': expansion.id, 'skipped': skipped}) + return before = {'state': (expansion.health or {}).get('state'), 'is_current': expansion.health_is_current, 'rules_version': (expansion.health or {}).get('rules_version')} started = time.time() @@ -102,8 +108,20 @@ def backfill(self, expansion_id): self.reasons[reason['code']] += 1 self.write({**report, 'health': health}) + def get_skip_reason(self, expansion): + if expansion.is_processing: + return 'being built' + is_up_to_date = expansion.health_is_current is True and \ + (expansion.health or {}).get('rules_version') == RULES_VERSION + # listed at the start, so a build since may have stored it + if self.options['all'] and not self.options['force'] and is_up_to_date: + return 'now current' + return None + def write(self, report): - if 'error' in report: + if 'skipped' in report: + self.stdout.write(f'SKIPPED {report["expansion"]}: {report["skipped"]}') + elif 'error' in report: self.stdout.write(f'FAILED {report["expansion"]}: {report["error"]}') else: health = report['health'] From ae9b874db47c566551519903412a680366b53caa Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Mon, 23 Nov 2026 13:25:17 +0530 Subject: [PATCH 3/6] OpenConceptLab/ocl_issues#3003 | the backfill's --pause waits only between expansions whose health it computes --- core/collections/tests/tests_health_backfill.py | 10 ++++++++++ .../management/commands/backfill_expansion_health.py | 9 ++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/core/collections/tests/tests_health_backfill.py b/core/collections/tests/tests_health_backfill.py index 5b03a6753..6141312da 100644 --- a/core/collections/tests/tests_health_backfill.py +++ b/core/collections/tests/tests_health_backfill.py @@ -120,6 +120,16 @@ def test_all_resumes_after_an_id_and_stops_at_the_limit(self): self.assertIn(f'{second.uri}:', out) self.assertNotIn(f'{third.uri}:', out) + def test_pause_waits_only_between_expansions_whose_health_was_computed(self): + second = self.another_expansion() + third = self.another_expansion() + self.clear(third) + Expansion.objects.filter(id=second.id).update(is_processing=True) + with patch('core.common.management.commands.backfill_expansion_health.time.sleep') as sleep: + self.run_command(self.expansion.uri, second.uri, third.uri, pause=2) + + sleep.assert_called_once_with(2) + def test_collection_version_uri_takes_its_default_expansion(self): self.assertIn(f'{self.expansion.uri}:', self.run_command(self.collection.uri)) diff --git a/core/common/management/commands/backfill_expansion_health.py b/core/common/management/commands/backfill_expansion_health.py index 19b1d62f9..e93223037 100644 --- a/core/common/management/commands/backfill_expansion_health.py +++ b/core/common/management/commands/backfill_expansion_health.py @@ -40,9 +40,8 @@ def handle(self, *args, **options): self.reasons = Counter() mode = 'APPLY' if options['apply'] else 'DRY RUN' self.stdout.write(f'{mode}. Rules version {RULES_VERSION}.') - for index, expansion_id in enumerate(self.get_expansion_ids()): - if index and options['pause']: - time.sleep(options['pause']) + self.has_computed = False + for expansion_id in self.get_expansion_ids(): self.backfill(expansion_id) totals = {**self.totals, 'states': dict(self.states), 'reasons': dict(self.reasons)} self.stdout.write(f'{mode} done: {json.dumps(totals, sort_keys=True)}') @@ -81,6 +80,10 @@ def backfill(self, expansion_id): self.totals[f'skipped_{skipped.replace(" ", "_")}'] += 1 self.write({'expansion': expansion.uri, 'id': expansion.id, 'skipped': skipped}) return + # waits only between computations: a skip costs nothing + if self.has_computed and self.options['pause']: + time.sleep(self.options['pause']) + self.has_computed = True before = {'state': (expansion.health or {}).get('state'), 'is_current': expansion.health_is_current, 'rules_version': (expansion.health or {}).get('rules_version')} started = time.time() From 47bea5dd2b161d4865aba733d5ca53552f6d772b Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Tue, 24 Nov 2026 09:01:01 +0530 Subject: [PATCH 4/6] OpenConceptLab/ocl_issues#3003 | the backfill takes default expansions only, waits before reading, honours --limit 0, prints ids and exits non-zero on a failure --- .../tests/tests_health_backfill.py | 70 ++++++++++++++++--- .../commands/backfill_expansion_health.py | 38 +++++++--- 2 files changed, 87 insertions(+), 21 deletions(-) diff --git a/core/collections/tests/tests_health_backfill.py b/core/collections/tests/tests_health_backfill.py index 6141312da..770749468 100644 --- a/core/collections/tests/tests_health_backfill.py +++ b/core/collections/tests/tests_health_backfill.py @@ -6,11 +6,13 @@ from django.core.management import call_command, CommandError from mock import patch -from core.collections.health import EMPTY, RULES_VERSION, ExpansionHealth +from core.collections.health import EMPTY, RULES_VERSION, ExpansionHealth, HEAD_MEMBER, MISMATCH from core.collections.models import Expansion from core.collections.tests.factories import OrganizationCollectionFactory from core.common.management.commands.backfill_expansion_health import Command from core.common.tests import OCLTestCase +from core.concepts.tests.factories import ConceptFactory +from core.mappings.tests.factories import MappingFactory class ExpansionHealthBackfillTest(OCLTestCase): @@ -37,9 +39,14 @@ def another_expansion(self): collection.save() return expansion - def run_command(self, *args, **kwargs): + def run_command(self, *args, fails=False, **kwargs): out = StringIO() - call_command('backfill_expansion_health', *args, stdout=out, **kwargs) + if fails: + # a run with a failure still reports every expansion, then exits non-zero + with self.assertRaises(CommandError): + call_command('backfill_expansion_health', *args, stdout=out, **kwargs) + else: + call_command('backfill_expansion_health', *args, stdout=out, **kwargs) return out.getvalue() def test_dry_run_computes_and_stores_nothing(self): @@ -86,7 +93,7 @@ def test_all_skips_and_reports_expansions_being_built(self): out = self.run_command(all=True, apply=True) - self.assertIn(f'SKIPPED {self.expansion.uri}: being built', out) + self.assertIn(f'SKIPPED {self.expansion.id} {self.expansion.uri}: being built', out) self.assertIn('"skipped_being_built": 1', out) self.assertEqual(self.stored(self.expansion), (None, None)) @@ -95,7 +102,7 @@ def test_a_uri_being_built_is_skipped_too(self): out = self.run_command(self.expansion.uri, apply=True) - self.assertIn(f'SKIPPED {self.expansion.uri}: being built', out) + self.assertIn(f'SKIPPED {self.expansion.id} {self.expansion.uri}: being built', out) self.assertEqual(self.stored(self.expansion), (None, None)) def test_all_skips_an_expansion_a_build_made_current_since_the_run_listed_it(self): @@ -105,7 +112,7 @@ def test_all_skips_an_expansion_a_build_made_current_since_the_run_listed_it(sel out = self.run_command(all=True) compute.assert_not_called() - self.assertIn(f'SKIPPED {current.uri}: now current', out) + self.assertIn(f'SKIPPED {current.id} {current.uri}: now current', out) self.assertIn('"skipped_now_current": 1', out) def test_all_resumes_after_an_id_and_stops_at_the_limit(self): @@ -137,17 +144,17 @@ def test_a_failure_is_reported_and_the_run_goes_on(self): other = self.another_expansion() results = [ValueError('boom'), {'state': EMPTY, 'reasons': []}] with patch.object(ExpansionHealth, 'compute', side_effect=results): - out = self.run_command(self.expansion.uri, other.uri) + out = self.run_command(self.expansion.uri, other.uri, fails=True) - self.assertIn(f'FAILED {self.expansion.uri}: ValueError: boom', out) + self.assertIn(f'FAILED {self.expansion.id} {self.expansion.uri}: ValueError: boom', out) self.assertIn(f'{other.uri}: ', out) self.assertIn('"failed": 1', out) def test_a_failure_while_applying_leaves_health_not_current(self): with patch.object(ExpansionHealth, 'compute', side_effect=ValueError('boom')): - out = self.run_command(self.expansion.uri, apply=True) + out = self.run_command(self.expansion.uri, apply=True, fails=True) - self.assertIn(f'FAILED {self.expansion.uri}: computing health failed', out) + self.assertIn(f'FAILED {self.expansion.id} {self.expansion.uri}: computing health failed', out) self.assertEqual(self.stored(self.expansion), (None, None)) def test_output_has_a_line_per_expansion(self): @@ -162,6 +169,49 @@ def test_output_has_a_line_per_expansion(self): self.assertEqual(reports[0]['health']['state'], EMPTY) self.assertTrue(reports[0]['is_default']) + def test_limit_zero_runs_nothing(self): + out = self.run_command(all=True, limit=0) + + self.assertNotIn(f'{self.expansion.uri}:', out) + + def test_an_expansion_that_isnt_its_versions_default_is_left_out(self): + other = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other') + self.clear(other) + + self.assertNotIn(f'{other.uri}:', self.run_command(all=True)) + self.assertIn(f'SKIPPED {other.id} {other.uri}: not a default expansion', self.run_command(other.uri)) + + def with_members(self): + concept = ConceptFactory() + mapping = MappingFactory(parent=concept.parent, from_concept=concept, to_concept=ConceptFactory()) + self.collection.add_expressions({'expressions': [concept.uri, mapping.uri]}, self.collection.created_by) + self.clear(self.expansion) + return self.members() + + def members(self): + expansion = Expansion.objects.get(id=self.expansion.id) + return (sorted(expansion.concepts.values_list('id', flat=True)), + sorted(expansion.mappings.values_list('id', flat=True))) + + def test_a_dry_run_on_an_expansion_with_members_changes_nothing(self): + members = self.with_members() + + out = self.run_command(self.expansion.uri) + + self.assertIn(f'{self.expansion.uri}: None ->', out) + self.assertEqual(self.members(), members) + self.assertEqual(self.stored(self.expansion), (None, None)) + + def test_apply_on_an_expansion_with_members_changes_only_its_health(self): + members = self.with_members() + + self.run_command(self.expansion.uri, apply=True) + + health, is_current = self.stored(self.expansion) + self.assertTrue(is_current) + self.assertEqual(health['members']['concepts'][HEAD_MEMBER] + health['members']['concepts'][MISMATCH], 1) + self.assertEqual(self.members(), members) + def test_needs_uris_or_all(self): with self.assertRaises(CommandError): self.run_command() diff --git a/core/common/management/commands/backfill_expansion_health.py b/core/common/management/commands/backfill_expansion_health.py index e93223037..934db9657 100644 --- a/core/common/management/commands/backfill_expansion_health.py +++ b/core/common/management/commands/backfill_expansion_health.py @@ -3,7 +3,7 @@ from collections import Counter from django.core.management import BaseCommand, CommandError -from django.db.models import Q +from django.db.models import F, Q from core.collections.constants import EXPANSION_HEALTH_TOGGLE from core.collections.health import RULES_VERSION, ExpansionHealth @@ -47,19 +47,23 @@ def handle(self, *args, **options): self.stdout.write(f'{mode} done: {json.dumps(totals, sort_keys=True)}') if options['output']: self.stdout.write(f'Full report: {options["output"]}') + if self.totals['failed']: + raise CommandError(f'{self.totals["failed"]} expansion(s) failed; rerun picks them up') def get_expansion_ids(self): if not self.options['all']: return [self.get_expansion(uri).id for uri in self.options['uris']] - # those being built are listed too, so a skipped one shows in the report + # those being built are listed too, so a skipped one shows in the report; health is kept for each version's + # default expansion only expansions = Expansion.objects.filter( - is_active=True, collection_version__is_active=True, id__gt=self.options['start_after_id']) + is_active=True, collection_version__is_active=True, collection_version__expansion_uri=F('uri'), + id__gt=self.options['start_after_id']) if not self.options['force']: # none yet, not current, or computed with older rules expansions = expansions.filter( Q(health__isnull=True) | ~Q(health_is_current=True) | ~Q(health__rules_version=RULES_VERSION)) ids = expansions.order_by('id').values_list('id', flat=True) - return list(ids[:self.options['limit']] if self.options['limit'] else ids) + return list(ids[:self.options['limit']] if self.options['limit'] is not None else ids) @staticmethod def get_expansion(uri): @@ -72,6 +76,10 @@ def get_expansion(uri): return expansion def backfill(self, expansion_id): + # after a computation, waits before reading the next expansion: a build that ends meanwhile isn't overwritten + if self.has_computed and self.options['pause']: + time.sleep(self.options['pause']) + self.has_computed = False expansion = Expansion.objects.filter(id=expansion_id).select_related('collection_version').first() if not expansion: return @@ -80,9 +88,6 @@ def backfill(self, expansion_id): self.totals[f'skipped_{skipped.replace(" ", "_")}'] += 1 self.write({'expansion': expansion.uri, 'id': expansion.id, 'skipped': skipped}) return - # waits only between computations: a skip costs nothing - if self.has_computed and self.options['pause']: - time.sleep(self.options['pause']) self.has_computed = True before = {'state': (expansion.health or {}).get('state'), 'is_current': expansion.health_is_current, 'rules_version': (expansion.health or {}).get('rules_version')} @@ -92,7 +97,7 @@ def backfill(self, expansion_id): except Exception as ex: # pylint: disable=broad-except health, error = None, f'{type(ex).__name__}: {ex}' else: - error = None if health else 'computing health failed; see the log' + error = None if health else self.get_apply_error(expansion) report = { 'expansion': expansion.uri, 'id': expansion.id, @@ -111,7 +116,16 @@ def backfill(self, expansion_id): self.reasons[reason['code']] += 1 self.write({**report, 'health': health}) + @staticmethod + def get_apply_error(expansion): + # changed while it computed: the result wasn't stored, and the run the change queued computes it + if Expansion.objects.filter(id=expansion.id, health_is_current=False).exists(): + return 'changed while it computed; a recompute is queued' + return 'computing health failed; see the log' + def get_skip_reason(self, expansion): + if expansion.collection_version.expansion_uri != expansion.uri: + return 'not a default expansion' if expansion.is_processing: return 'being built' is_up_to_date = expansion.health_is_current is True and \ @@ -122,15 +136,17 @@ def get_skip_reason(self, expansion): return None def write(self, report): + # each line names the id, as --start-after-id resumes by it if 'skipped' in report: - self.stdout.write(f'SKIPPED {report["expansion"]}: {report["skipped"]}') + self.stdout.write(f'SKIPPED {report["id"]} {report["expansion"]}: {report["skipped"]}') elif 'error' in report: - self.stdout.write(f'FAILED {report["expansion"]}: {report["error"]}') + self.stdout.write(f'FAILED {report["id"]} {report["expansion"]}: {report["error"]}') else: health = report['health'] reasons = ' '.join(sorted(reason['code'] for reason in health['reasons'])) self.stdout.write( - f'{report["expansion"]}: {report["before"]["state"]} -> {health["state"]} {reasons}'.rstrip()) + f'{report["id"]} {report["expansion"]}: {report["before"]["state"]} -> {health["state"]} ' + f'{reasons}'.rstrip()) if self.options['output']: with open(self.options['output'], 'a', encoding='utf-8') as file: file.write(json.dumps(report, default=str) + '\n') From 6eb76f7f7e0373e98e6f560f0f960092ffdb9a1d Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Tue, 24 Nov 2026 09:48:02 +0530 Subject: [PATCH 5/6] OpenConceptLab/ocl_issues#3003 | The backfill tests claim the default before seeding, so a just-built expansion is current --- core/collections/tests/tests_health_backfill.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/core/collections/tests/tests_health_backfill.py b/core/collections/tests/tests_health_backfill.py index 770749468..f1860387d 100644 --- a/core/collections/tests/tests_health_backfill.py +++ b/core/collections/tests/tests_health_backfill.py @@ -19,9 +19,7 @@ class ExpansionHealthBackfillTest(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() + self.expansion = self.default_expansion(self.collection) self.clear(self.expansion) @staticmethod @@ -32,12 +30,14 @@ def clear(expansion, **kwargs): def stored(expansion): return Expansion.objects.values_list('health', 'health_is_current').get(id=expansion.id) + @staticmethod + def default_expansion(collection): + # the default before it seeds, as a version's own build makes it, so the seed stores current health + return Expansion.persist( + index=False, collection_version=collection, mnemonic='autoexpand-HEAD', claim_default=True) + def another_expansion(self): - collection = OrganizationCollectionFactory() - expansion = Expansion.persist(index=False, collection_version=collection, mnemonic='autoexpand-HEAD') - collection.expansion_uri = expansion.uri - collection.save() - return expansion + return self.default_expansion(OrganizationCollectionFactory()) def run_command(self, *args, fails=False, **kwargs): out = StringIO() From 915ab93fa164f7c1e32476ce04fed53f6d3cba62 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Tue, 24 Nov 2026 11:58:54 +0530 Subject: [PATCH 6/6] OpenConceptLab/ocl_issues#3003 | The backfill tells a store that lost to a change by the revision, whatever the change left --- .../collections/tests/tests_health_backfill.py | 18 ++++++++++++++++++ .../commands/backfill_expansion_health.py | 14 +++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/core/collections/tests/tests_health_backfill.py b/core/collections/tests/tests_health_backfill.py index f1860387d..308cda1c2 100644 --- a/core/collections/tests/tests_health_backfill.py +++ b/core/collections/tests/tests_health_backfill.py @@ -4,6 +4,7 @@ from io import StringIO from django.core.management import call_command, CommandError +from django.db.models import F from mock import patch from core.collections.health import EMPTY, RULES_VERSION, ExpansionHealth, HEAD_MEMBER, MISMATCH @@ -157,6 +158,23 @@ def test_a_failure_while_applying_leaves_health_not_current(self): self.assertIn(f'FAILED {self.expansion.id} {self.expansion.uri}: computing health failed', out) self.assertEqual(self.stored(self.expansion), (None, None)) + def test_a_change_while_applying_is_reported_as_one_whatever_it_left(self): + computed = [] + + def compute(_health): + if not computed: + # a repository mark while it computes leaves the row None, not False + Expansion.objects.filter(id=self.expansion.id).update( + health_is_current=None, health_revision=F('health_revision') + 1) + computed.append(1) + return {'state': EMPTY, 'reasons': []} + + with patch.object(ExpansionHealth, 'compute', autospec=True, side_effect=compute): + out = self.run_command(self.expansion.uri, apply=True, fails=True) + + self.assertIn( + f'FAILED {self.expansion.id} {self.expansion.uri}: changed while it computed, so it was not stored', out) + def test_output_has_a_line_per_expansion(self): with tempfile.TemporaryDirectory() as directory: output = os.path.join(directory, 'report.jsonl') diff --git a/core/common/management/commands/backfill_expansion_health.py b/core/common/management/commands/backfill_expansion_health.py index 934db9657..bfe0c57da 100644 --- a/core/common/management/commands/backfill_expansion_health.py +++ b/core/common/management/commands/backfill_expansion_health.py @@ -92,12 +92,13 @@ def backfill(self, expansion_id): before = {'state': (expansion.health or {}).get('state'), 'is_current': expansion.health_is_current, 'rules_version': (expansion.health or {}).get('rules_version')} started = time.time() + revision = self.get_revision(expansion) try: health = expansion.update_health() if self.options['apply'] else ExpansionHealth(expansion).compute() except Exception as ex: # pylint: disable=broad-except health, error = None, f'{type(ex).__name__}: {ex}' else: - error = None if health else self.get_apply_error(expansion) + error = None if health else self.get_apply_error(expansion, revision) report = { 'expansion': expansion.uri, 'id': expansion.id, @@ -117,10 +118,13 @@ def backfill(self, expansion_id): self.write({**report, 'health': health}) @staticmethod - def get_apply_error(expansion): - # changed while it computed: the result wasn't stored, and the run the change queued computes it - if Expansion.objects.filter(id=expansion.id, health_is_current=False).exists(): - return 'changed while it computed; a recompute is queued' + def get_revision(expansion): + return Expansion.objects.filter(id=expansion.id).values_list('health_revision', flat=True).first() + + def get_apply_error(self, expansion, revision): + # any mark or store moves the revision, whether it leaves the row False or None; a failed compute doesn't + if self.get_revision(expansion) != revision: + return 'changed while it computed, so it was not stored' return 'computing health failed; see the log' def get_skip_reason(self, expansion):