Skip to content
Open
237 changes: 237 additions & 0 deletions core/collections/tests/tests_health_backfill.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
import json
import os
import tempfile
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
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):
def setUp(self):
super().setUp()
self.collection = OrganizationCollectionFactory()
self.expansion = self.default_expansion(self.collection)
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)

@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):
return self.default_expansion(OrganizationCollectionFactory())

def run_command(self, *args, fails=False, **kwargs):
out = StringIO()
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):
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_and_reports_expansions_being_built(self):
Expansion.objects.filter(id=self.expansion.id).update(is_processing=True)

out = self.run_command(all=True, apply=True)

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))

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.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):
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.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):
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_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))

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, fails=True)

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, fails=True)

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')
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_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()
with self.assertRaises(CommandError):
self.run_command(self.expansion.uri, all=True)
156 changes: 156 additions & 0 deletions core/common/management/commands/backfill_expansion_health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import json
import time
from collections import Counter

from django.core.management import BaseCommand, CommandError
from django.db.models import F, 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. '
'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):
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}.')
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)}')
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']]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Nit (optional): explicit URIs don't skip expansions being built. --all skips them, but a URI on the command line is computed mid-build. With --apply, that stores health judged from part of the members until the build's own update replaces it. The same check belongs in backfill().

# 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, 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'] is not None 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):
# 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()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Nit (optional): an expansion that becomes current mid-run is still recomputed. --all lists the ids once, so one that a build makes current during a long run gets computed again when its turn comes. Unless --force is given, backfill() could re-check, skip it, and count it as skipped.

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
self.has_computed = True
Comment on lines +78 to +91

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Point 2: waits before reading the next expansion, not between reading and computing, so a build that ends during the wait isn't overwritten.

Suggested change
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
# 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
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
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
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()
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, revision)
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})

@staticmethod
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):
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 \
(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):
# each line names the id, as --start-after-id resumes by it
if 'skipped' in report:
self.stdout.write(f'SKIPPED {report["id"]} {report["expansion"]}: {report["skipped"]}')
elif 'error' in report:
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["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')
Loading