Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/collections/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
class Collection(DirtyFieldsMixin, VersionCompareMixin, ConceptContainerModel):
OBJECT_TYPE = COLLECTION_TYPE
OBJECT_VERSION_TYPE = COLLECTION_VERSION_TYPE
COMPARES_BY_SOURCE = True

es_fields = {
'collection_type': {'sortable': True, 'filterable': True, 'facet': True, 'exact': True},
Expand Down Expand Up @@ -1998,6 +1999,7 @@ def default_expansion_parameters():
class Expansion(VersionCompareMixin, BaseResourceModel):
# expansions are rebuilt in place and are too dynamic to be worth persisting a changelog for
PERSIST_CHANGELOG = False
COMPARES_BY_SOURCE = True
COMPARES_HEAD_AS_NEWEST = False # an expansion's is_head means it's the default, which can be the older one
SYSTEM_VERSION_UNRESOLVED_TYPE = SYSTEM_VERSION_PARAMETER_TYPE
REPO_VERSION_RELATIONS = (
Expand Down
201 changes: 139 additions & 62 deletions core/common/checksums.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import time

from django.apps import apps
from django.conf import settings
from django.db import models
from django.db.models import Q
Expand Down Expand Up @@ -135,14 +136,57 @@ def get_map_id(resource_map, identity):
return (resource_map.get(identity) or {}).get('id')


def get_source_key(source_id, mnemonic):
return f'{source_id}/{mnemonic}'


def label_members(resource, *maps):
"""
Relabels maps built by source: a member is labelled by its id, or by its address when the maps
have that id from several sources. Returns the maps, the label of each source key, and the id and
the source of each member labelled by its address.
"""
from core.sources.models import Source
keys = {key for _map in maps for group in ('active', 'retired') for key in _map[group]}
source_ids = {}
for key in keys:
source_id, mnemonic = key.split('/', 1)
source_ids.setdefault(mnemonic, set()).add(source_id)
shared = {mnemonic for mnemonic, ids in source_ids.items() if len(ids) > 1}
source_uris = {
str(_id): uri for _id, uri in Source.objects.filter(
id__in={_id for mnemonic in shared for _id in source_ids[mnemonic]}).values_list('id', 'uri')
} if shared else {}

labels, shared_members = {}, {}
for key in keys:
source_id, mnemonic = key.split('/', 1)
labels[key] = mnemonic
if mnemonic in shared:
source_uri = source_uris.get(source_id)
if not source_uri: # a saved map can name a source deleted since
labels[key] = key
continue
labels[key] = f'{source_uri}{resource}/{mnemonic}/'
shared_members[labels[key]] = {'id': mnemonic, 'source': source_uri}
Comment thread
snyaggarwal marked this conversation as resolved.
Resolved

maps = [
{group: {labels[key]: info for key, info in _map[group].items()} for group in ('active', 'retired')}
for _map in maps
]
return maps, labels, shared_members


class ChecksumDiff:
def __init__( # pylint: disable=too-many-arguments
self, resources1=None, resources2=None, resources1_map=None, resources2_map=None,
identity='mnemonic', verbosity=0):
identity='mnemonic', verbosity=0, labels=None, shared_members=None):
self.resources1 = resources1 # older version resources (queryset; unused if resources1_map given)
self.resources2 = resources2 # newer version resources (queryset; unused if resources2_map given)
self.identity = identity
self.verbosity = verbosity
self.labels = labels # of members from several sources, see label_members; None when they're from one
self.shared_members = shared_members or {}
self.same_standard = {}
self.same_smart = {}
self.changed_smart = {}
Expand All @@ -160,19 +204,23 @@ def __init__( # pylint: disable=too-many-arguments
self._retired = None

@staticmethod
def build_map(resources, identity='mnemonic'):
def build_map(resources, identity='mnemonic', by_source=False):
resources = list(resources)
ChecksumDiff._repair_incomplete_checksums(resources)

active = {}
retired = {}
for resource in resources:
target = retired if resource.retired else active
target[get(resource, identity)] = {
key = get(resource, identity)
target[get_source_key(resource.parent_id, key) if by_source else key] = {
'checksums': resource.checksums,
'id': resource.id
}
return {'active': active, 'retired': retired}
result = {'active': active, 'retired': retired}
if by_source:
result['by_source'] = True
return result

@staticmethod
def _repair_incomplete_checksums(resources):
Expand Down Expand Up @@ -393,6 +441,14 @@ def pretty_print_dict(self, d, indent=0): # pragma: no cover
def print(self):
print(self.pretty_print_dict(self.result))

def get_label(self, source_id, mnemonic):
"""What a member is called in this diff. None when it isn't a member."""
return mnemonic if self.labels is None else self.labels.get(get_source_key(source_id, mnemonic))

def get_member_summary(self, label):
"""A member's id, and its source when the id alone doesn't tell it apart."""
return self.shared_members.get(label) or {'id': label}

def get_db_id_for(self, diff_key, identity):
"""Return the concrete resource DB id represented by a changelog diff key."""
if diff_key == 'changed_retired':
Expand All @@ -413,8 +469,8 @@ class ChecksumChangelog:
DIFF_KEYS = ('new', 'removed', 'changed_retired', 'changed_major', 'changed_minor')
MAPPING_SUMMARY_FIELDS = (
'id', 'mnemonic', 'map_type', 'external_id', 'from_concept_code', 'to_concept_code', 'from_source_url',
'to_source_url', 'from_concept__mnemonic', 'from_concept__versioned_object_id', 'from_concept__parent_id',
'to_concept__mnemonic',
'to_source_url', 'from_source', 'from_concept__mnemonic', 'from_concept__versioned_object_id',
'from_concept__parent_id', 'to_concept__mnemonic',
)

def __init__(self, concepts_diff, mappings_diff, identity='mnemonic', verbosity=0): # pylint: disable=too-many-arguments
Expand All @@ -433,9 +489,17 @@ def get_diff_size(self):
if isinstance(entry, dict)
)

def get_mapping_summary(self, mapping, mapping_id=None, v1_mapping=None):
def _get_from_concept_label(self, mapping):
"""The label that the mapping's from concept has in the concepts' diff."""
code = get(mapping, 'from_concept_code') or get(mapping, 'from_concept.mnemonic')
if not code:
return None
source_id = get(mapping, 'from_concept.parent_id') or get(mapping, 'from_source_id')
return self.concepts_diff.get_label(source_id, code)

def get_mapping_summary(self, mapping, mapping_id, v1_mapping=None):
summary = {
'id': mapping_id or get(mapping, self.identity),
**self.mappings_diff.get_member_summary(mapping_id),
'from_concept': mapping.from_concept_code or get(mapping.from_concept, 'mnemonic'),
'from_source': mapping.from_source_url,
'to_concept': mapping.to_concept_code or get(mapping.to_concept, 'mnemonic'),
Expand Down Expand Up @@ -520,12 +584,11 @@ def _get_display_names(concept_ids):
display_names[concept.id] = display_name.replace('"', "'") if display_name else display_name
return display_names

@staticmethod
def _get_new_changed_only_concept_ids(mappings_cache, same_concept_ids, changed_only):
def _get_new_changed_only_concept_ids(self, mappings_cache, same_concept_ids, changed_only):
concept_ids = set()
for mapping in mappings_cache.values():
code = mapping.from_concept_code or get(mapping, 'from_concept.mnemonic')
if mapping.from_concept_id and code in same_concept_ids and code not in changed_only:
label = self._get_from_concept_label(mapping)
if mapping.from_concept_id and label in same_concept_ids and label not in changed_only:
concept_ids.add(mapping.from_concept_id)
return concept_ids

Expand Down Expand Up @@ -580,6 +643,25 @@ def _v1_mapping_for(self, mnemonic, mapping_db_id, mappings_cache):
return mappings_cache.get(v1_id)
return None

@staticmethod
def _set_shared_member_urls(model_name, diff, sections):
"""The addresses of the compared revisions, for members that their id alone doesn't open."""
ids = {}
for key, section in sections.items():
for label in section:
if label in diff.shared_members:
prev_id = get_map_id(diff.resources1_map, label) if key.startswith('changed_') else None
ids[(key, label)] = {'version_url': diff.get_db_id_for(key, label), 'prev_version_url': prev_id}
if not ids:
return

uris = {}
model = apps.get_model(f'{model_name.lower()}s', model_name)
for batch in chunks(sorted({_id for urls in ids.values() for _id in urls.values() if _id}), 5000):
uris.update(model.objects.filter(id__in=batch).values_list('id', 'uri'))
for (key, label), urls in ids.items():
sections[key][label].update({field: uris[_id] for field, _id in urls.items() if _id in uris})

def process(self): # pylint: disable=too-many-locals,too-many-branches,too-many-statements
concepts_result = {}
mappings_result = {}
Expand Down Expand Up @@ -619,7 +701,7 @@ def process(self): # pylint: disable=too-many-locals,too-many-branches,too-many
if concept_display_name:
concept_display_name = concept_display_name.replace('"', "'")
summary = {
'id': concept_id,
**self.concepts_diff.get_member_summary(concept_id),
'display_name': concept_display_name
}
if include_changelog_enrichment and concept:
Expand Down Expand Up @@ -652,7 +734,7 @@ def process(self): # pylint: disable=too-many-locals,too-many-branches,too-many
):
v1_mapping = self._v1_mapping_for(mnemonic, mapping.id, mappings_cache)
mappings_diff_summary[mapping_diff_key].append(
self.get_mapping_summary(mapping, v1_mapping=v1_mapping)
self.get_mapping_summary(mapping, mnemonic, v1_mapping=v1_mapping)
)
traversed_mappings.add(mnemonic)
if mappings_diff_summary:
Expand Down Expand Up @@ -688,20 +770,22 @@ def process(self): # pylint: disable=too-many-locals,too-many-branches,too-many
if include_changelog_enrichment and key in ('changed_major', 'changed_minor'):
v1_mapping = self._v1_mapping_for(mapping_id, mapping_db_id, mappings_cache)
mapping_summary = self.get_mapping_summary(mapping, mapping_id, v1_mapping=v1_mapping)
from_concept_code = get(mapping, 'from_concept_code') or get(mapping, 'from_concept.mnemonic')
if from_concept_code and from_concept_code in same_concept_ids:
from_concept_label = self._get_from_concept_label(mapping)
if from_concept_label and from_concept_label in same_concept_ids:
changed_only = concepts_result.setdefault('changed_mappings_only', {})
if from_concept_code not in changed_only:
changed_only[from_concept_code] = {
'id': from_concept_code,
if from_concept_label not in changed_only:
changed_only[from_concept_label] = {
**self.concepts_diff.get_member_summary(from_concept_label),
'display_name': display_names.get(mapping.from_concept_id),
'mappings': {}
}
changed_only[from_concept_code]['mappings'].setdefault(key, []).append(mapping_summary)
changed_only[from_concept_label]['mappings'].setdefault(key, []).append(mapping_summary)
else:
section_summary[mapping_id] = mapping_summary
if section_summary:
mappings_result[key] = section_summary
self._set_shared_member_urls('Concept', self.concepts_diff, concepts_result)
self._set_shared_member_urls('Mapping', self.mappings_diff, mappings_result)
self.result = {
'concepts': concepts_result,
'mappings': mappings_result,
Expand All @@ -713,12 +797,13 @@ class VersionCompareMixin:
JSON_FORMAT = 'json'
PERSIST_CHANGELOG = True # expansions are too dynamic/rebuilt-in-place to persist; see Expansion override
COMPARES_HEAD_AS_NEWEST = True # whatever its date; not for expansions, see Expansion override
COMPARES_BY_SOURCE = False # by id and source, where members come from several sources and can share an id

@classmethod
def get_checksum_map(cls, version, resource):
queryset = getattr(version, f'get_{resource}_queryset')().only('mnemonic', 'checksums', 'retired')
queryset = getattr(version, f'get_{resource}_queryset')().only('mnemonic', 'checksums', 'retired', 'parent')
if not cls.PERSIST_CHANGELOG:
return ChecksumDiff.build_map(queryset)
return ChecksumDiff.build_map(queryset, by_source=cls.COMPARES_BY_SOURCE)

from core.repos.models import VersionChecksumMap
field = f'{resource}_map'
Expand All @@ -728,30 +813,42 @@ def get_checksum_map(cls, version, resource):
and version.last_child_update > cached.updated_at
)
existing = None if is_stale else getattr(cached, field)
if not existing:
existing = ChecksumDiff.build_map(queryset)
if not existing or (cls.COMPARES_BY_SOURCE and not existing.get('by_source')):
existing = ChecksumDiff.build_map(queryset, by_source=cls.COMPARES_BY_SOURCE)
setattr(cached, field, existing)
cached.save()
return existing

@classmethod
def get_diff(cls, version1, version2, resource, verbosity):
maps = [cls.get_checksum_map(version, resource) for version in (version1, version2)]
labels, shared_members = None, None
if cls.COMPARES_BY_SOURCE:
maps, labels, shared_members = label_members(resource, *maps)
diff = ChecksumDiff(
resources1_map=maps[0], resources2_map=maps[1], verbosity=verbosity,
labels=labels, shared_members=shared_members)
diff.process()
return diff

@classmethod
def find_or_build_changelog(cls, version1, version2):
from core.repos.models import VersionChangelog
changelog = VersionChangelog.find_or_build(version1, version2)
if cls.COMPARES_BY_SOURCE and not get(changelog.extras, 'by_source'):
# what was saved compared by id alone
changelog.changelog, changelog.comparison = {}, {}
changelog.extras = {**(changelog.extras or {}), 'by_source': True}
return changelog

@classmethod
def compare(cls, version1, version2, verbosity=0):
"""
version1 is the older version
version2 is the newer version
"""
concepts_diff = ChecksumDiff(
resources1_map=cls.get_checksum_map(version1, 'concepts'),
resources2_map=cls.get_checksum_map(version2, 'concepts'),
verbosity=verbosity,
)
mappings_diff = ChecksumDiff(
resources1_map=cls.get_checksum_map(version1, 'mappings'),
resources2_map=cls.get_checksum_map(version2, 'mappings'),
verbosity=verbosity,
)
concepts_diff.process()
mappings_diff.process()
concepts_diff = cls.get_diff(version1, version2, 'concepts', verbosity)
mappings_diff = cls.get_diff(version1, version2, 'mappings', verbosity)
return VersionCompareMixin.get_compare_result(concepts_diff, mappings_diff, version1, version2)

@staticmethod
Expand Down Expand Up @@ -787,18 +884,8 @@ def changelog(cls, version1, version2, verbosity=0):
# categories (which ChecksumChangelog.process() needs) without also materializing
# id lists for the same_* categories (which nothing here reads -- same-concept
# membership is checked against same_standard/same_smart directly, not the result).
concepts_diff = ChecksumDiff(
resources1_map=cls.get_checksum_map(version1, 'concepts'),
resources2_map=cls.get_checksum_map(version2, 'concepts'),
verbosity=DIFF_RESOURCE_IDS_VERBOSITY
)
mappings_diff = ChecksumDiff(
resources1_map=cls.get_checksum_map(version1, 'mappings'),
resources2_map=cls.get_checksum_map(version2, 'mappings'),
verbosity=DIFF_RESOURCE_IDS_VERBOSITY
)
concepts_diff.process()
mappings_diff.process()
concepts_diff = cls.get_diff(version1, version2, 'concepts', DIFF_RESOURCE_IDS_VERBOSITY)
mappings_diff = cls.get_diff(version1, version2, 'mappings', DIFF_RESOURCE_IDS_VERBOSITY)
log = ChecksumChangelog(concepts_diff, mappings_diff, verbosity=verbosity)
log.process()
result = VersionCompareMixin.get_changelog_result(concepts_diff, mappings_diff, version1,
Expand Down Expand Up @@ -836,25 +923,16 @@ def get_changelog_result( # pylint: disable=too-many-arguments

@classmethod
def save_changelog_and_comparison(cls, uri1, uri2):
from core.repos.models import VersionChangelog
# A version deleted since this was asked for leaves nothing to compare
version1, version2 = cls._get_versions(uri1, uri2, raise_if_missing=False)
if not version1:
logger.info('Skipping changelog: %s or %s no longer exists', uri1, uri2)
return None
changelog = VersionChangelog.find_or_build(version1, version2)
changelog = cls.find_or_build_changelog(version1, version2)
start_time = time.time()

concepts_diff = ChecksumDiff(
resources1_map=cls.get_checksum_map(version1, 'concepts'),
resources2_map=cls.get_checksum_map(version2, 'concepts'),
verbosity=DIFF_RESOURCE_IDS_VERBOSITY)
mappings_diff = ChecksumDiff(
resources1_map=cls.get_checksum_map(version1, 'mappings'),
resources2_map=cls.get_checksum_map(version2, 'mappings'),
verbosity=DIFF_RESOURCE_IDS_VERBOSITY)
concepts_diff.process()
mappings_diff.process()
concepts_diff = cls.get_diff(version1, version2, 'concepts', DIFF_RESOURCE_IDS_VERBOSITY)
mappings_diff = cls.get_diff(version1, version2, 'mappings', DIFF_RESOURCE_IDS_VERBOSITY)

log = ChecksumChangelog(concepts_diff, mappings_diff, verbosity=CHANGELOG_ENRICHMENT_VERBOSITY)
log.process()
Expand Down Expand Up @@ -883,8 +961,7 @@ def run_diff( # pylint: disable=too-many-arguments
return result
return cls.compare(version1, version2, verbosity)

from core.repos.models import VersionChangelog
changelog = VersionChangelog.find_or_build(version1, version2)
changelog = cls.find_or_build_changelog(version1, version2)
# HEAD is a moving target -- a previously saved changelog/comparison against HEAD is only
# trustworthy if nothing has changed in HEAD since it was saved. last_child_update (not
# updated_at) is used because it only moves when concepts/mappings actually change.
Expand Down
Loading
Loading