From cc94bd41e9e8cd0e848ef1c867ad4a1fa27bc99d Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 19 Nov 2026 10:00:06 +0530 Subject: [PATCH 1/8] OpenConceptLab/ocl_online#655 | Isolated source versions: a seeding import replaces HEAD content, metadata and hierarchy, and versions record seeded_from --- core/common/checksums.py | 321 ++++---- core/common/mixins.py | 23 + core/common/models.py | 4 + core/common/swagger_parameters.py | 6 + core/common/tasks.py | 131 ++-- core/common/tests.py | 5 +- core/common/utils.py | 11 +- core/concepts/models.py | 171 ++++- core/concepts/views.py | 32 +- core/importers/constants.py | 3 + core/importers/importer.py | 144 +++- core/importers/models.py | 300 ++++++-- core/importers/tests.py | 717 +++++++++++++++++- core/importers/views.py | 37 +- core/integration_tests/tests_sources.py | 33 +- core/mappings/models.py | 9 +- core/settings.py | 2 + core/sources/constants.py | 18 + .../migrations/0048_source_versioning_mode.py | 18 + .../migrations/0049_source_seeded_from.py | 54 ++ core/sources/models.py | 117 ++- core/sources/serializers.py | 4 +- 22 files changed, 1767 insertions(+), 393 deletions(-) create mode 100644 core/sources/migrations/0048_source_versioning_mode.py create mode 100644 core/sources/migrations/0049_source_seeded_from.py diff --git a/core/common/checksums.py b/core/common/checksums.py index 164b1b1cd..a9e488846 100644 --- a/core/common/checksums.py +++ b/core/common/checksums.py @@ -5,6 +5,8 @@ from ocldev.checksum import Checksum as ChecksumBase from pydash import get +from core.common.utils import chunks + # Return only aggregate counts for changed resource groups. SUMMARY_VERBOSITY = 0 @@ -403,12 +405,29 @@ def get_db_id_for(self, diff_key, identity): class ChecksumChangelog: + CONCEPTS_BATCH_SIZE = 1000 + 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', + ) + def __init__(self, concepts_diff, mappings_diff, identity='mnemonic', verbosity=0): # pylint: disable=too-many-arguments self.concepts_diff = concepts_diff self.mappings_diff = mappings_diff self.identity = identity self.verbosity = verbosity self.result = {} + self.enrichment_skipped = False + + def get_diff_size(self): + return sum( + len(entry[self.identity]) + for diff in (self.concepts_diff, self.mappings_diff) + for entry in (diff.result.get(key) for key in self.DIFF_KEYS) + if isinstance(entry, dict) + ) def get_mapping_summary(self, mapping, mapping_id=None, v1_mapping=None): summary = { @@ -419,7 +438,7 @@ def get_mapping_summary(self, mapping, mapping_id=None, v1_mapping=None): 'to_source': mapping.to_source_url, 'map_type': mapping.map_type, } - if self.verbosity >= CHANGELOG_ENRICHMENT_VERBOSITY: + if self.verbosity >= CHANGELOG_ENRICHMENT_VERBOSITY and not self.enrichment_skipped: summary['external_id'] = getattr(mapping, 'external_id', None) if v1_mapping is not None: summary['prev_to_concept'] = ( @@ -446,66 +465,88 @@ def _collect_v1_v2_ids(self, diff, diff_obj): ids.add(v1_id) return ids - def _build_concepts_cache(self, diff_keys): - """Batch-fetch concepts with names/descriptions for enrich mode (avoids N+1 queries).""" + def _get_concepts_cache(self, key, mnemonics, enriched): + """Fetch one batch of concepts (and their v1 state) with names, and descriptions when enriched.""" from core.concepts.models import Concept - ids = self._collect_v1_v2_ids( - {k: self.concepts_diff.result.get(k, False) for k in diff_keys}, - self.concepts_diff, - ) - return { - c.id: c - for c in Concept.objects.filter(id__in=ids).prefetch_related('names', 'descriptions') - } + ids = self._collect_v1_v2_ids({key: {self.identity: mnemonics}}, self.concepts_diff) + parents = {} + cache = {} + prefetch = ('names', 'descriptions') if enriched else ('names',) + for concept in Concept.objects.filter(id__in=ids).prefetch_related(*prefetch): + if concept.parent_id not in parents: + parents[concept.parent_id] = concept.parent + concept.parent = parents[concept.parent_id] + cache[concept.id] = concept + return cache + + def _get_mapping_db_ids(self, key, mnemonics, enriched): + """The db ids of one batch of diff'd mappings, plus their v1 ids for prev_* when enriched.""" + ids = set() + for mnemonic in mnemonics: + db_id = self.mappings_diff.get_db_id_for(key, mnemonic) + if db_id: + ids.add(db_id) + if enriched and key in ('changed_major', 'changed_minor'): + v1_id = get_map_id(self.mappings_diff.resources1_map, mnemonic) + if v1_id and v1_id != db_id: + ids.add(v1_id) + return ids - def _build_mappings_cache(self, diff_keys): - """Batch-fetch mappings for enrich mode (to resolve v1 state of changed mappings).""" + def _get_mappings_cache(self, ids): + """Fetch one batch of mappings with only the fields the summary uses.""" from core.mappings.models import Mapping - ids = self._collect_v1_v2_ids( - {k: self.mappings_diff.result.get(k, False) for k in diff_keys}, - self.mappings_diff, - ) return { - m.id: m - for m in Mapping.objects.filter(id__in=ids).select_related('from_concept', 'to_concept') + mapping.id: mapping + for batch in chunks(sorted(ids), 5000) + for mapping in Mapping.objects.filter(id__in=batch).select_related( + 'from_concept', 'to_concept').only(*self.MAPPING_SUMMARY_FIELDS) } - def _build_mapping_diff_index(self, diff_keys, mappings_cache=None): + @staticmethod + def _get_display_names(concept_ids): + """Display names of one batch of concepts, with their names prefetched and their sources loaded once.""" + from core.concepts.models import Concept + parents = {} + display_names = {} + for concept in Concept.objects.filter(id__in=concept_ids).prefetch_related('names'): + if concept.parent_id not in parents: + parents[concept.parent_id] = concept.parent + concept.parent = parents[concept.parent_id] + display_name = concept.display_name + 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): + 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: + concept_ids.add(mapping.from_concept_id) + return concept_ids + + def _build_mapping_diff_index(self, diff_keys): """ - Group every new/removed/changed mapping by its from_concept's versioned_object_id, in a - single batched pass. Without this, attaching diff'd mappings to their concept required - one query PER concept PER diff key, each with an IN-clause spanning every mapping in that - category -- for a source with tens of thousands of changed mappings and concepts, that's - effectively quadratic and dominates both runtime and memory. + Group every new/removed/changed mapping by its from_concept's versioned_object_id, as + (mnemonic, db id) pairs only: the mappings themselves are fetched per concept batch. """ from core.mappings.models import Mapping - ids_by_key = {} - all_ids = set() + index = {} for key in diff_keys: diff = self.mappings_diff.result.get(key, False) - if isinstance(diff, dict): - db_ids = [self.mappings_diff.get_db_id_for(key, mnemonic) for mnemonic in diff[self.identity]] - ids_by_key[key] = db_ids - all_ids.update(db_ids) - - if mappings_cache: - # mappings_cache already covers every id here (plus v1 state for changed items) -- - # reuse it instead of fetching and holding the same rows in memory a second time. - mappings_by_id = mappings_cache - else: - mappings_by_id = { - m.id: m - for m in Mapping.objects.filter(id__in=all_ids).select_related('from_concept', 'to_concept') - } - - index = {} - for key, ids in ids_by_key.items(): - for mapping_id in ids: - mapping = mappings_by_id.get(mapping_id) - from_concept = get(mapping, 'from_concept') - if not from_concept: - continue - index.setdefault(from_concept.versioned_object_id, {}).setdefault(key, []).append(mapping) + if not isinstance(diff, dict): + continue + mnemonics_by_id = {} + for mnemonic in diff[self.identity]: + db_id = self.mappings_diff.get_db_id_for(key, mnemonic) + if db_id: + mnemonics_by_id.setdefault(db_id, []).append(mnemonic) + for batch in chunks(sorted(mnemonics_by_id), 5000): + for mapping_id, versioned_object_id in Mapping.objects.filter(id__in=batch).values_list( + 'id', 'from_concept__versioned_object_id'): + if versioned_object_id: + index.setdefault(versioned_object_id, {}).setdefault(key, []).extend( + (mnemonic, mapping_id) for mnemonic in mnemonics_by_id[mapping_id]) return index @staticmethod @@ -536,75 +577,83 @@ def _v1_mapping_for(self, mnemonic, mapping_db_id, mappings_cache): return None def process(self): # pylint: disable=too-many-locals,too-many-branches,too-many-statements - from core.mappings.models import Mapping - from core.concepts.models import Concept concepts_result = {} mappings_result = {} traversed_mappings = set() traversed_concepts = set() - diff_keys = ['new', 'removed', 'changed_retired', 'changed_major', 'changed_minor'] + diff_keys = self.DIFF_KEYS include_changelog_enrichment = self.verbosity >= CHANGELOG_ENRICHMENT_VERBOSITY + if include_changelog_enrichment and self.get_diff_size() > settings.CHANGELOG_ENRICHMENT_MAX_RESOURCES: + include_changelog_enrichment = False + self.enrichment_skipped = True - concepts_cache = self._build_concepts_cache(diff_keys) if include_changelog_enrichment else {} - mappings_cache = self._build_mappings_cache(diff_keys) if include_changelog_enrichment else {} - mapping_diff_index = self._build_mapping_diff_index(diff_keys, mappings_cache) + mapping_diff_index = self._build_mapping_diff_index(diff_keys) for key in diff_keys: # pylint: disable=too-many-nested-blocks diff = self.concepts_diff.result.get(key, False) if isinstance(diff, dict): section_summary = {} - for concept_id in diff[self.identity]: - if concept_id in traversed_concepts: - continue - traversed_concepts.add(concept_id) - concept_db_id = self.concepts_diff.get_db_id_for(key, concept_id) - if include_changelog_enrichment: + for batch in chunks(diff[self.identity], self.CONCEPTS_BATCH_SIZE): + concepts_cache = self._get_concepts_cache(key, batch, include_changelog_enrichment) + batch_mapping_diffs = {} + for concept in concepts_cache.values(): + for mapping_diff_key, entries in mapping_diff_index.get( + concept.versioned_object_id, {}).items(): + batch_mapping_diffs.setdefault(mapping_diff_key, []).extend( + mnemonic for mnemonic, _ in entries) + mappings_cache = self._get_mappings_cache({ + _id for mapping_diff_key, mnemonics in batch_mapping_diffs.items() + for _id in self._get_mapping_db_ids( + mapping_diff_key, mnemonics, include_changelog_enrichment)}) + for concept_id in batch: + if concept_id in traversed_concepts: + continue + traversed_concepts.add(concept_id) + concept_db_id = self.concepts_diff.get_db_id_for(key, concept_id) concept = concepts_cache.get(concept_db_id) - else: - concept = Concept.objects.filter(id=concept_db_id).first() - concept_display_name = get(concept, 'display_name') - if concept_display_name: - concept_display_name = concept_display_name.replace('"', "'") - summary = { - 'id': concept_id, - 'display_name': concept_display_name - } - if include_changelog_enrichment and concept: - summary['concept_class'] = getattr(concept, 'concept_class', None) - summary['datatype'] = getattr(concept, 'datatype', None) - summary['names'] = self._names_list(concept) - summary['descriptions'] = self._descriptions_list(concept) - if key in ('changed_major', 'changed_minor'): - v1_id = get_map_id(self.concepts_diff.resources1_map, concept_id) - if v1_id and v1_id != concept_db_id: - v1_concept = concepts_cache.get(v1_id) - if v1_concept: - summary['prev_names'] = self._names_list(v1_concept) - summary['prev_descriptions'] = self._descriptions_list(v1_concept) - summary['prev_concept_class'] = getattr(v1_concept, 'concept_class', None) - summary['prev_datatype'] = getattr(v1_concept, 'datatype', None) - mappings_diff_summary = {} - for mapping_diff_key, mappings in mapping_diff_index.get( - get(concept, 'versioned_object_id'), {}).items(): - for mapping in mappings: - mnemonic = get(mapping, self.identity) - if mnemonic in traversed_mappings: - continue - if mapping_diff_key not in mappings_diff_summary: - mappings_diff_summary[mapping_diff_key] = [] - v1_mapping = None - if ( - include_changelog_enrichment and - mapping_diff_key in ('changed_major', 'changed_minor') - ): - 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) - ) - traversed_mappings.add(mnemonic) - if mappings_diff_summary: - summary['mappings'] = mappings_diff_summary - section_summary[concept_id] = summary + concept_display_name = get(concept, 'display_name') + if concept_display_name: + concept_display_name = concept_display_name.replace('"', "'") + summary = { + 'id': concept_id, + 'display_name': concept_display_name + } + if include_changelog_enrichment and concept: + summary['concept_class'] = getattr(concept, 'concept_class', None) + summary['datatype'] = getattr(concept, 'datatype', None) + summary['names'] = self._names_list(concept) + summary['descriptions'] = self._descriptions_list(concept) + if key in ('changed_major', 'changed_minor'): + v1_id = get_map_id(self.concepts_diff.resources1_map, concept_id) + if v1_id and v1_id != concept_db_id: + v1_concept = concepts_cache.get(v1_id) + if v1_concept: + summary['prev_names'] = self._names_list(v1_concept) + summary['prev_descriptions'] = self._descriptions_list(v1_concept) + summary['prev_concept_class'] = getattr(v1_concept, 'concept_class', None) + summary['prev_datatype'] = getattr(v1_concept, 'datatype', None) + mappings_diff_summary = {} + for mapping_diff_key, entries in mapping_diff_index.get( + get(concept, 'versioned_object_id'), {}).items(): + for mnemonic, mapping_db_id in entries: + mapping = mappings_cache.get(mapping_db_id) + if mapping is None or mnemonic in traversed_mappings: + continue + if mapping_diff_key not in mappings_diff_summary: + mappings_diff_summary[mapping_diff_key] = [] + v1_mapping = None + if ( + include_changelog_enrichment and + mapping_diff_key in ('changed_major', 'changed_minor') + ): + 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) + ) + traversed_mappings.add(mnemonic) + if mappings_diff_summary: + summary['mappings'] = mappings_diff_summary + section_summary[concept_id] = summary if section_summary: concepts_result[key] = section_summary # Read the raw same_standard/same_smart dicts directly rather than the exposed @@ -619,36 +668,34 @@ def process(self): # pylint: disable=too-many-locals,too-many-branches,too-many diff = self.mappings_diff.result.get(key, False) if isinstance(diff, dict): section_summary = {} - for mapping_id in diff[self.identity]: - if mapping_id in traversed_mappings: - continue - traversed_mappings.add(mapping_id) - mapping_db_id = self.mappings_diff.get_db_id_for(key, mapping_id) - if mappings_cache: + for batch in chunks(diff[self.identity], self.CONCEPTS_BATCH_SIZE): + batch = [mapping_id for mapping_id in batch if mapping_id not in traversed_mappings] + mappings_cache = self._get_mappings_cache( + self._get_mapping_db_ids(key, batch, include_changelog_enrichment)) + display_names = self._get_display_names(self._get_new_changed_only_concept_ids( + mappings_cache, same_concept_ids, concepts_result.get('changed_mappings_only', {}))) + for mapping_id in batch: + if mapping_id in traversed_mappings: + continue + traversed_mappings.add(mapping_id) + mapping_db_id = self.mappings_diff.get_db_id_for(key, mapping_id) mapping = mappings_cache.get(mapping_db_id) - else: - mapping = Mapping.objects.filter(id=mapping_db_id).first() - v1_mapping = None - 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: - if 'changed_mappings_only' not in concepts_result: - concepts_result['changed_mappings_only'] = {} - if from_concept_code not in concepts_result['changed_mappings_only']: - concept_display_name = get(mapping.from_concept, 'display_name') - if concept_display_name: - concept_display_name = concept_display_name.replace('"', "'") - concepts_result['changed_mappings_only'][from_concept_code] = { - 'id': from_concept_code, - 'display_name': concept_display_name, - 'mappings': {} - } - mappings_dict = concepts_result['changed_mappings_only'][from_concept_code]['mappings'] - mappings_dict.setdefault(key, []).append(mapping_summary) - else: - section_summary[mapping_id] = mapping_summary + v1_mapping = None + 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: + 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, + 'display_name': display_names.get(mapping.from_concept_id), + 'mappings': {} + } + changed_only[from_concept_code]['mappings'].setdefault(key, []).append(mapping_summary) + else: + section_summary[mapping_id] = mapping_summary if section_summary: mappings_result[key] = section_summary self.result = { @@ -771,6 +818,8 @@ def get_changelog_result( # pylint: disable=too-many-arguments }, **log.result } + if log.enrichment_skipped: + result['meta']['enrichment_skipped'] = True if verbosity > 0: concepts_diff.set_concise_result() mappings_diff.set_concise_result() diff --git a/core/common/mixins.py b/core/common/mixins.py index 46448885e..dbccb2d3b 100644 --- a/core/common/mixins.py +++ b/core/common/mixins.py @@ -1,4 +1,5 @@ import logging +from copy import deepcopy from math import ceil from urllib import parse from urllib.parse import urlencode @@ -670,6 +671,8 @@ class SourceChildMixin(ChecksumModel): _counted = models.BooleanField(default=True, null=True, blank=True) _index = models.BooleanField(default=True) + ISOLATED_VERSION_DEFAULTS = {'extras': {}, 'retired': False} + # 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 @@ -1141,6 +1144,26 @@ def __update_latest_version(self, index, is_latest_version, parent, remove_paren if add_parent: self.sources.add(parent) + def set_version_fields(self, data, fields, isolated=False): + for field in fields: + if isolated: + value = data.get(field) + setattr(self, field, deepcopy(self.ISOLATED_VERSION_DEFAULTS.get(field)) if value is None else value) + else: + setattr(self, field, data.get(field, getattr(self, field))) + + def restore_to_head(self): + versioned_object = self.versioned_object + parent = versioned_object.parent + if not versioned_object.is_active: + versioned_object.is_active = True + versioned_object.save(update_fields=['is_active']) + versioned_object.sources.add(parent) + latest_version = versioned_object.get_latest_version() + if latest_version: + latest_version.sources.add(parent) + return latest_version + def unmark_latest_version(self, index=True, parent=None): parent = parent or self.parent self.__update_latest_version(index, False, parent, True, False) diff --git a/core/common/models.py b/core/common/models.py index 9d4fab2b0..92cfc8d52 100644 --- a/core/common/models.py +++ b/core/common/models.py @@ -1293,6 +1293,7 @@ def persist_new_version_in_transaction( # pylint: disable=too-many-arguments cursor.execute('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ') # Serialize version creation with destructive child operations on the HEAD repository. head = cls.objects.select_for_update().get(id=head.id) + obj.apply_version_metadata_to_head(head) obj.update_version_data(head) obj.save(**kwargs) # the default is settled while HEAD is locked, so a queued task can't see another HEAD @@ -1339,6 +1340,9 @@ def index_resources_for_self_as_latest_released(self, only_update=False): # pyl def get_expansion_choice(self, expansion=None): # pylint: disable=unused-argument return None + def apply_version_metadata_to_head(self, head): + pass + @classmethod def persist_changes(cls, obj, updated_by, original_schema, **kwargs): # pylint: disable=too-many-locals,too-many-branches errors = {} diff --git a/core/common/swagger_parameters.py b/core/common/swagger_parameters.py index 0f1b4a621..f22c9cd68 100644 --- a/core/common/swagger_parameters.py +++ b/core/common/swagger_parameters.py @@ -111,6 +111,12 @@ f"When omitted, imports of up to {settings.IMPORT_INDEX_MAX_LINES:,} lines are indexed and larger " "ones aren't" ) +seed_from_import_param = openapi.Parameter( + 'seed_from_import', openapi.IN_QUERY, type=openapi.TYPE_STRING, default='false', + description="true | false. The import is one whole source version: its concepts and mappings, then exactly one " + "Source Version line. HEAD keeps only what the import contains, and the version is seeded from the " + "import, unless some of the content fails to import" +) file_upload_param = openapi.Parameter( 'file', openapi.IN_FORM, description="JSON Content File (json, csv or zip)", type=openapi.TYPE_FILE ) diff --git a/core/common/tasks.py b/core/common/tasks.py index aec4f2cf3..5adea3897 100644 --- a/core/common/tasks.py +++ b/core/common/tasks.py @@ -16,7 +16,7 @@ from django.core.management import call_command from django.core.paginator import Paginator from django.db import DatabaseError -from django.db.models import Exists, OuterRef, F +from django.db.models import Exists, OuterRef from django.template.loader import render_to_string from django.utils import timezone from django_elasticsearch_dsl.registries import registry @@ -267,40 +267,48 @@ def bulk_import(to_import, username, update_if_exists): @app.task(base=QueueOnceCustomTask, bind=True, retry_kwargs={'max_retries': 0}) -def bulk_import_parallel_inline(self, to_import, username, update_if_exists, threads=5, index=None): # pylint: disable=too-many-arguments +def bulk_import_parallel_inline( # pylint: disable=too-many-arguments + self, to_import, username, update_if_exists, threads=5, index=None, isolated_version=False): from core.importers.models import BulkImportParallelRunner try: importer = BulkImportParallelRunner( content=to_import, username=username, update_if_exists=update_if_exists, - parallel=threads, self_task_id=self.request.id, index=index + parallel=threads, self_task_id=self.request.id, index=index, isolated_version=isolated_version ) except JSONDecodeError as ex: return {'error': f"Invalid JSON ({ex.msg})"} except ValidationError as ex: - return {'error': f"Invalid Input ({ex.message})"} + return {'error': f"Invalid Input ({'; '.join(ex.messages)})"} return importer.run() -@app.task(base=QueueOnceCustomTask, retry_kwargs={'max_retries': 0}) -def bulk_import_inline(to_import, username, update_if_exists, index=None): +@app.task(bind=True, base=QueueOnceCustomTask, retry_kwargs={'max_retries': 0}) +def bulk_import_inline( # pylint: disable=too-many-arguments + self, to_import, username, update_if_exists, index=None, isolated_version=False): from core.importers.models import BulkImportInline return BulkImportInline( - content=to_import, username=username, update_if_exists=update_if_exists, index=index).run() + content=to_import, username=username, update_if_exists=update_if_exists, index=index, + isolated_version=isolated_version, self_task_id=self.request.id).run() # pylint: disable=too-many-arguments @app.task(bind=True, base=QueueOnceCustomTask, retry_kwargs={'max_retries': 0}) -def bulk_import_new(self, path, username, owner_type, owner, import_type='default', index=None): +def bulk_import_new( # pylint: disable=too-many-arguments + self, path, username, owner_type, owner, import_type='default', index=None, isolated_version=False): from core.importers.importer import Importer task_id = self.request.id - return Importer(task_id, path, username, owner_type, owner, import_type, index).run() + return Importer(task_id, path, username, owner_type, owner, import_type, index, isolated_version).run() # pylint: disable=too-many-arguments @app.task(retry_kwargs={'max_retries': 0}, compression='gzip') -def bulk_import_subtask(path, username, owner_type, owner, resource_type, files, index=True): +def bulk_import_subtask( # pylint: disable=too-many-arguments + path, username, owner_type, owner, resource_type, files, index=True, isolated=False, isolated_version=False, + previous_subtask_ids=None, import_task_id=None): from core.importers.importer import ImporterSubtask - return ImporterSubtask(path, username, owner_type, owner, resource_type, files, index).run() + return ImporterSubtask( + path, username, owner_type, owner, resource_type, files, index, isolated, isolated_version, + previous_subtask_ids, import_task_id).run() @app.task(retry_kwargs={'max_retries': 0}, compression='gzip') @@ -336,11 +344,11 @@ def import_finisher(task_id): @app.task(bind=True, retry_kwargs={'max_retries': 0}) -def bulk_import_parts_inline(self, input_list, username, update_if_exists, index=True): +def bulk_import_parts_inline(self, input_list, username, update_if_exists, index=True, isolated=False): # pylint: disable=too-many-arguments from core.importers.models import BulkImportInline return BulkImportInline( content=None, username=username, update_if_exists=update_if_exists, input_list=input_list, - self_task_id=self.request.id, skip_hierarchy_tasks=True, index=index + self_task_id=self.request.id, skip_hierarchy_tasks=True, index=index, isolated=isolated ).run() @@ -534,7 +542,8 @@ def process_hierarchy_for_new_concept(concept_id, initial_version_id, parent_con acks_late=True, reject_on_worker_lost=True ) def process_hierarchy_for_concept_version( - latest_version_id, prev_version_id, parent_concept_uris, create_parent_version): + latest_version_id, prev_version_id, parent_concept_uris, create_parent_version, + create_removed_parent_versions=True, update_head=True): """ Executed when a new concept version is created with new, updated or existing hierarchy 1. Associates parent concepts to the latest concept version. @@ -554,9 +563,10 @@ def process_hierarchy_for_concept_version( uri__in=parent_concept_uris) if parent_concept_uris else Concept.objects.none() latest_version._parent_concepts = parent_concepts # pylint: disable=protected-access latest_version.set_parent_concepts_from_uris(create_parent_version) - latest_version.versioned_object.parent_concepts.set(latest_version.parent_concepts.all()) + if update_head: + latest_version.versioned_object.parent_concepts.set(latest_version.parent_concepts.all()) - if prev_version: + if prev_version and create_removed_parent_versions: removed_parent_urls = [ url for url in old_parents if url not in list(latest_version.parent_concept_urls) ] @@ -696,72 +706,14 @@ def index_expansion_mappings(expansion_id, count=None, mapping_ids=None): # pyl @app.task -def make_hierarchy(concept_map): # pragma: no cover # pylint: disable=too-many-locals - from core.concepts.models import Concept, HierarchicalConcepts - - def chunks(values, size=5000): - values = list(values) - for index in range(0, len(values), size): - yield values[index:index + size] - - def resolve(uris): - """uri -> (id, versioned_object_id); the lowest id wins for duplicate uris, like .first()""" - resolved = {} - for batch in chunks(uris): - for concept_id, versioned_object_id, uri in Concept.objects.filter(uri__in=batch).order_by( - '-id').values_list('id', 'versioned_object_id', 'uri'): - resolved[uri] = (concept_id, versioned_object_id) - return resolved - - def latest_versions(versioned_object_ids): - """versioned_object_id -> id of its newest active latest version, like Concept.get_latest_version()""" - latest = {} - for batch in chunks(versioned_object_ids): - for versioned_object_id, concept_id in Concept.objects.filter( - versioned_object_id__in=batch, is_latest_version=True, is_active=True - ).exclude(id=F('versioned_object_id')).order_by('created_at').values_list('versioned_object_id', 'id'): - latest[versioned_object_id] = concept_id # ascending created_at, so the newest wins - return latest - - parents = resolve(concept_map.keys()) - parent_latest = latest_versions({versioned_object_id for _, versioned_object_id in parents.values()}) - children = resolve({ - url for parent_uri, urls in concept_map.items() - if parent_uri in parents and parents[parent_uri][1] in parent_latest for url in urls}) - child_latest = latest_versions({versioned_object_id for _, versioned_object_id in children.values()}) - - pairs = set() - for parent_uri, urls in concept_map.items(): - if parent_uri not in parents: - logger.info('Could not find parent %s', parent_uri) - continue - parent_id = parent_latest.get(parents[parent_uri][1]) - if not parent_id: - logger.info('Could not find parent %s latest_version', parent_uri) - continue - for url in urls: - if url not in children: - continue - child_id, child_versioned_object_id = children[url] - pairs.add((child_id, parent_id)) - if child_versioned_object_id in child_latest: - pairs.add((child_latest[child_versioned_object_id], parent_id)) - else: - logger.info('Could not find child %s latest_version', url) - - if not pairs: - return - existing = set() - parent_id_set = {parent for _, parent in pairs} - for batch in chunks({child for child, _ in pairs}): - existing.update( - HierarchicalConcepts.objects.filter( - child_id__in=batch, parent_id__in=parent_id_set).values_list('child_id', 'parent_id')) - HierarchicalConcepts.objects.bulk_create( - [HierarchicalConcepts(child_id=child, parent_id=parent) for child, parent in pairs - existing], - batch_size=5000 - ) - logger.info('Added %s hierarchy links', len(pairs - existing)) +def make_hierarchy(concept_map): + """concept_map: parent uri -> child uris. Adds the links, never removes any.""" + from core.concepts.models import ImportHierarchy + child_map = {} + for parent_uri, child_uris in concept_map.items(): + for child_uri in child_uris: + child_map.setdefault(child_uri, []).append(parent_uri) + ImportHierarchy.from_uri_map(child_map).apply() @app.task(ignore_result=True, base=QueueOnceCustomTask) @@ -987,6 +939,21 @@ def index_source_mappings( source.clear_mappings_cache() +@app.task( + autoretry_for=(Exception, WorkerLostError, ), retry_backoff=True, retry_backoff_max=600, max_retries=5, + acks_late=True, reject_on_worker_lost=True +) +def index_dropped_source_children(source_id, concept_ids, mapping_ids, recount=True): + """ + Reindexes one chunk of the concepts and mappings an import-seeded version dropped from HEAD, after the commit, + and recounts HEAD when asked. Retried with backoff; its Task records a final failure. + """ + from core.sources.models import Source + source = Source.objects.filter(id=source_id).first() + if source: + source.index_dropped_children(concept_ids, mapping_ids, recount) + + @app.task( bind=True, autoretry_for=(Exception, WorkerLostError, ), retry_backoff=True, retry_backoff_max=600, max_retries=2, acks_late=True, reject_on_worker_lost=True diff --git a/core/common/tests.py b/core/common/tests.py index a4b98b857..2a6d197db 100644 --- a/core/common/tests.py +++ b/core/common/tests.py @@ -2442,14 +2442,15 @@ def test_bulk_import_new_passes_index(self, importer_mock): 'some/path', 'ocladmin', 'Organization', 'org1', 'npm', False ) - importer_mock.assert_called_once_with(ANY, 'some/path', 'ocladmin', 'Organization', 'org1', 'npm', False) + importer_mock.assert_called_once_with( + ANY, 'some/path', 'ocladmin', 'Organization', 'org1', 'npm', False, False) @patch('core.importers.importer.ImporterSubtask') def test_bulk_import_subtask_passes_index(self, subtask_mock): bulk_import_subtask('some/path', 'ocladmin', 'Organization', 'org1', 'Concept', ['f1.json'], False) subtask_mock.assert_called_once_with( - 'some/path', 'ocladmin', 'Organization', 'org1', 'Concept', ['f1.json'], False) + 'some/path', 'ocladmin', 'Organization', 'org1', 'Concept', ['f1.json'], False, False, False, None, None) @patch('core.common.tasks.chord') def test_bulk_import_queue(self, chord_mock): diff --git a/core/common/utils.py b/core/common/utils.py index 64eb8c4c5..26555c410 100644 --- a/core/common/utils.py +++ b/core/common/utils.py @@ -429,7 +429,8 @@ def es_get(url, **kwargs): def queue_bulk_import( # pylint: disable=too-many-arguments,too-many-locals - to_import, import_queue, username, update_if_exists, threads=None, inline=False, sub_task=False, index=None + to_import, import_queue, username, update_if_exists, threads=None, inline=False, sub_task=False, index=None, + isolated_version=False ): """ Used to queue bulk imports. It assigns a bulk import task to a specified import queue or a random one. @@ -456,13 +457,9 @@ def queue_bulk_import( # pylint: disable=too-many-arguments,too-many-locals task_func = bulk_import_parallel_inline args = (to_import, username, update_if_exists, threads) else: - # TODO: bulk_import_inline is unreachable from the current view layer — - # import_response always passes `parallel_threads = request.data.get('parallel') or 5` - # which is always truthy, so the `elif threads` branch above is always taken. - # Consider removing bulk_import_inline and this branch once confirmed no external - # callers rely on it (check API consumers and the test suite first). + # BulkImportInlineView reaches this with threads=None task_func = bulk_import_inline - args = (*args, index) + args = (*args, index, True) if isolated_version else (*args, index) else: task_func = bulk_import task = get_queue_task_names(import_queue, username, name=task_func.__name__) diff --git a/core/concepts/models.py b/core/concepts/models.py index 58c81fab7..85730dd77 100644 --- a/core/concepts/models.py +++ b/core/concepts/models.py @@ -15,7 +15,7 @@ from core.common.tasks import process_hierarchy_for_new_concept, process_hierarchy_for_concept_version, \ process_hierarchy_for_new_parent_concept_version, update_mappings_concept from core.common.utils import generate_temp_version, drop_version, \ - startswith_temp_version, decode_string + startswith_temp_version, decode_string, chunks, is_url_encoded_string, encode_string from core.concepts.constants import CONCEPT_TYPE, LOCALES_FULLY_SPECIFIED, LOCALES_SHORT, LOCALES_SEARCH_INDEX_TERM, \ CONCEPT_WAS_RETIRED, CONCEPT_IS_ALREADY_RETIRED, CONCEPT_IS_ALREADY_NOT_RETIRED, CONCEPT_WAS_UNRETIRED, \ ALREADY_EXISTS, CONCEPT_REGEX, MAX_LOCALES_LIMIT, \ @@ -303,6 +303,7 @@ def get_validation_errors(error): CHECKSUM_INCLUSIONS = [ 'extras', 'concept_class', 'datatype', 'retired' ] + ISOLATED_VERSION_DEFAULTS = {**SourceChildMixin.ISOLATED_VERSION_DEFAULTS, 'datatype': 'None'} # $cascade as hierarchy attributes cascaded_entries = None @@ -627,7 +628,7 @@ def create_initial_version(cls, concept, **kwargs): @classmethod def create_new_version_for( cls, instance, data, user, create_parent_version=True, add_prev_version_children=True, - _hierarchy_processing=False, is_patch=False + _hierarchy_processing=False, is_patch=False, isolated=False ): # pylint: disable=too-many-arguments,too-many-locals mappings_payload = data.pop('mappings_payload', None) prev_latest = Concept.objects.filter( @@ -636,12 +637,10 @@ def create_new_version_for( instance.id = None # Clear id so it is persisted as a new object instance.version = data.get('version', None) instance.concept_class = data.get('concept_class', instance.concept_class) - instance.datatype = data.get('datatype', instance.datatype) - instance.extras = data.get('extras', instance.extras) - instance.external_id = data.get('external_id', instance.external_id) instance.comment = data.get('update_comment') or data.get('comment') - instance.retire_reason = data.get('retire_reason', instance.retire_reason) - instance.retired = data.get('retired', instance.retired) + instance.set_version_fields( + data, ('datatype', 'extras', 'external_id', 'retire_reason', 'retired'), isolated) + instance._isolated = isolated # pylint: disable=protected-access if is_patch: prev = instance.versions.exclude(id=instance.id).filter(is_latest_version=True).first() new_names = ConceptName.build(data.get('names', [])) if 'names' in data else ( @@ -658,11 +657,13 @@ def create_new_version_for( instance.cloned_names = compact(new_names) instance.cloned_descriptions = compact(new_descriptions) - if has_parent_concept_uris_attr: + prev_parent_uris = list(prev_latest.parent_concept_urls) if prev_latest else [] + if isolated or has_parent_concept_uris_attr: parent_concept_uris = cls.get_viewable_parent_uris( - parent_concept_uris or [], user, lambda: prev_latest.parent_concept_urls if prev_latest else []) + parent_concept_uris or [], user, lambda: prev_parent_uris) else: - parent_concept_uris = list(prev_latest.parent_concept_urls) if prev_latest else [] + parent_concept_uris = prev_parent_uris + has_parent_change = isolated and {drop_version(uri) for uri in parent_concept_uris} != set(prev_parent_uris) errors = instance.save_as_new_version( user=user, @@ -670,7 +671,7 @@ def create_new_version_for( parent_concept_uris=parent_concept_uris, add_prev_version_children=add_prev_version_children, _hierarchy_processing=_hierarchy_processing, - skip_duplicate_version_check=bool(mappings_payload) + skip_duplicate_version_check=bool(mappings_payload) or has_parent_change ) if errors or mappings_payload is None: @@ -1242,7 +1243,8 @@ def update_versioned_object(self): concept.remove_locales() concept.set_locales(self.names.all(), ConceptName) concept.set_locales(self.descriptions.all(), ConceptDescription) - concept.parent_concepts.set(self.parent_concepts.all()) + if not get(self, '_isolated'): # a seeding import sets HEAD's parents when it commits the version + concept.parent_concepts.set(self.parent_concepts.all()) concept.concept_class = self.concept_class concept.datatype = self.datatype concept.retired = self.retired @@ -1275,12 +1277,13 @@ def _process_prev_latest_version_hierarchy(self, prev_latest, add_prev_version_c def _process_latest_version_hierarchy(self, prev_latest, parent_concept_uris=None, create_parent_version=True): task = process_hierarchy_for_concept_version + args = (self.id, get(prev_latest, 'id'), parent_concept_uris, create_parent_version) + if get(self, '_isolated'): + args = (*args, False, False) if get(settings, 'TEST_MODE', False): - task(self.id, get(prev_latest, 'id'), parent_concept_uris, create_parent_version) + task(*args) else: - task.apply_async( - (self.id, get(prev_latest, 'id'), parent_concept_uris, create_parent_version), - queue='concurrent', permanent=False) + task.apply_async(args, queue='concurrent', permanent=False) @staticmethod def validate_locales_limit(names, descriptions): @@ -1428,12 +1431,16 @@ def get_hierarchy_ids(self): return ids def get_hierarchy_related_queryset(self, relation, versioned=False): - """The concepts linked through relation, in one query: their HEADs, or with versioned the linked versions.""" + """ + The concepts linked through relation, in one query: their HEADs, or with versioned the linked versions. + Read from HEAD, concepts dropped from HEAD are left out; a version's links stay as they were. + """ own, other = {'child_concepts': ('parent', 'child'), 'parent_concepts': ('child', 'parent')}[relation] links = HierarchicalConcepts.objects.filter(**{f'{own}_id__in': self.get_hierarchy_ids()}) if versioned: return Concept.objects.filter(id__in=links.values(f'{other}_id')).exclude(id=F('versioned_object_id')) - return Concept.objects.filter(id__in=links.values(f'{other}__versioned_object_id')) + queryset = Concept.objects.filter(id__in=links.values(f'{other}__versioned_object_id')) + return queryset.filter(is_active=True) if self.is_versioned_object else queryset @staticmethod def annotate_has_children(queryset): @@ -1448,6 +1455,58 @@ def annotate_has_children(queryset): has_children_annotated=Exists(own) | (Q(is_latest_version=True) & Exists(of_head)) | (Q(id=F('versioned_object_id')) & Exists(of_latest))) + @staticmethod + def get_import_hierarchy_map(input_list, include_parentless=False): + hierarchy_map = {} + for line in input_list: + if (line.get('type', '') or '').lower() != 'concept': + continue + parent_urls = line.get('parent_concept_urls') or [] + concept_id = line.get('id') + owner = line.get('owner') + source = line.get('source') + if (parent_urls or include_parentless) and concept_id and owner and source: + owner_type = line.get('owner_type', '').lower() + owner_prefix = 'users' if owner_type in ['user', 'users'] else 'orgs' + if not is_url_encoded_string(concept_id): + concept_id = encode_string(concept_id, safe='') + hierarchy_map[f'/{owner_prefix}/{owner}/sources/{source}/concepts/{concept_id}/'] = parent_urls + return hierarchy_map + + @classmethod + def reconcile_import_hierarchy(cls, hierarchy_map, user, replace_head=False): + ImportHierarchy.from_uri_map(hierarchy_map, user).apply(replace_head) + + @classmethod + def get_versioned_objects_by_uri(cls, uris): + resolved = {} + for batch in chunks(sorted(uris), 5000): + for uri, concept_id, source_id in cls.objects.filter( + uri__in=batch, id=F('versioned_object_id')).values_list('uri', 'id', 'parent_id'): + resolved[uri] = (concept_id, source_id) + return resolved + + @classmethod + def get_latest_version_ids_by_versioned_object_id(cls, versioned_object_ids): + latest = {} + for batch in chunks(sorted(compact(versioned_object_ids)), 5000): + for versioned_object_id, concept_id in cls.objects.filter( + versioned_object_id__in=batch, is_latest_version=True, is_active=True + ).exclude(id=F('versioned_object_id')).order_by('created_at').values_list('versioned_object_id', 'id'): + latest[versioned_object_id] = concept_id + return latest + + def get_version_hierarchy_queryset(self, relation, repo_version): + if relation == 'parent_concepts': + member = repo_version.concepts.filter(versioned_object_id=self.versioned_object_id).first() + if not member: + return Concept.objects.none() + return repo_version.concepts.filter( + versioned_object_id__in=member.parent_concepts.values('versioned_object_id')) + return repo_version.concepts.filter( + id__in=Concept.objects.filter( + parent_concepts__versioned_object_id=self.versioned_object_id).values('id')) + def child_concept_queryset(self): return self.get_hierarchy_related_queryset('child_concepts') @@ -1969,3 +2028,79 @@ def get_serializer_class(verbose=False, version=False, brief=False, cascade=Fals @staticmethod def get_brief_serializer(): return Concept.get_serializer_class(brief=True) + + +class ImportHierarchy: + """ + An import's parent links, resolved once into versioned object ids. apply() links each child's versioned object + and latest version to its parents' latest versions, add-only, or replaces the versioned objects' links. + """ + CHUNK_SIZE = 5000 + + def __init__(self, links): + self.links = links # child versioned object id -> parent versioned object ids + self.latest = Concept.get_latest_version_ids_by_versioned_object_id( + {*links, *(parent_id for parent_ids in links.values() for parent_id in parent_ids)}) + + @classmethod + def from_uri_map(cls, hierarchy_map, user=None): + """hierarchy_map: child uri -> parent uris. With a user, only children it can edit and parents it can view.""" + from core.sources.models import Source + resolved = Concept.get_versioned_objects_by_uri( + {*hierarchy_map, *(uri for uris in hierarchy_map.values() for uri in uris)}) + editable = viewable = None + if user: + sources = Source.objects.filter(id__in={source_id for _, source_id in resolved.values()}) + editable = {source.id for source in sources if source.has_edit_access(user)} + viewable = {source.id for source in sources if source.has_view_access(user)} + links = {} + for child_uri, parent_uris in hierarchy_map.items(): + child_id, child_source_id = resolved.get(child_uri, (None, None)) + if not child_id or (editable is not None and child_source_id not in editable): + continue + links.setdefault(child_id, set()).update( + resolved[uri][0] for uri in parent_uris + if uri in resolved and (viewable is None or resolved[uri][1] in viewable)) + return cls(links) + + def apply(self, replace_head=False): + for batch in chunks(sorted(self.links), self.CHUNK_SIZE): + parents = { + child_id: {self.latest[parent_id] for parent_id in self.links[child_id] if parent_id in self.latest} + for child_id in batch + } + pairs = { + (self.latest[child_id], parent_id) for child_id, parent_ids in parents.items() + if child_id in self.latest for parent_id in parent_ids} + if replace_head: + self.replace_links(parents) + else: + pairs.update( + (child_id, parent_id) for child_id, parent_ids in parents.items() for parent_id in parent_ids) + self.add_links(pairs) + + @staticmethod + def add_links(pairs): + if not pairs: + return + existing = set(HierarchicalConcepts.objects.filter( + child_id__in={child_id for child_id, _ in pairs}, parent_id__in={parent_id for _, parent_id in pairs} + ).values_list('child_id', 'parent_id')) + HierarchicalConcepts.objects.bulk_create( + [HierarchicalConcepts(child_id=child_id, parent_id=parent_id) for child_id, parent_id in pairs - existing], + batch_size=5000) + + @staticmethod + def replace_links(parents): + """parents: child versioned object id -> the parent ids it should have, and no others.""" + existing = {} + for child_id, parent_id in HierarchicalConcepts.objects.filter( + child_id__in=parents).values_list('child_id', 'parent_id'): + existing.setdefault(child_id, set()).add(parent_id) + changed = [child_id for child_id, parent_ids in parents.items() if existing.get(child_id, set()) != parent_ids] + if changed: + HierarchicalConcepts.objects.filter(child_id__in=changed).delete() + HierarchicalConcepts.objects.bulk_create( + [HierarchicalConcepts(child_id=child_id, parent_id=parent_id) + for child_id in changed for parent_id in parents[child_id]], + batch_size=5000) diff --git a/core/concepts/views.py b/core/concepts/views.py index fe7f016ae..70c1b218f 100644 --- a/core/concepts/views.py +++ b/core/concepts/views.py @@ -24,7 +24,7 @@ from core.collections.documents import CollectionDocument from core.common import ERRBIT_LOGGER from core.common.constants import ( - HEAD, INCLUDE_INVERSE_MAPPINGS_PARAM, INCLUDE_RETIRED_PARAM, ACCESS_TYPE_NONE, LIST_DEFAULT_LIMIT) + HEAD, LATEST, INCLUDE_INVERSE_MAPPINGS_PARAM, INCLUDE_RETIRED_PARAM, ACCESS_TYPE_NONE, LIST_DEFAULT_LIMIT) from core.common.exceptions import Http400, Http403, Http409 from core.common.mixins import ListWithHeadersMixin, ConceptDictionaryMixin from core.capabilities.constants import MAPPER_MATCH_OPERATIONS_CAPABILITY_ID @@ -602,7 +602,29 @@ def get_clone_to_source(self): return source -class ConceptChildrenView(ConceptBaseView, ListWithHeadersMixin): +class ConceptHierarchyMixin: + def get_source_version(self): + """The source version named in the URL, or None for HEAD and collection URLs.""" + source, version = self.kwargs.get('source'), self.kwargs.get('version') + if not source or not version or version == HEAD: + return None + from core.sources.models import Source + if 'org' in self.kwargs: + filters = {'organization__mnemonic': self.kwargs['org']} + else: + filters = {'user__username': self.request.user.username if self.user_is_self else self.kwargs.get('user')} + if version == LATEST: + return Source.find_latest_released_version_by({**filters, 'mnemonic': source}) + return Source.get_version(source, version, filters) + + def get_hierarchy_queryset(self, instance, relation): + repo_version = self.get_source_version() + if repo_version: + return instance.get_version_hierarchy_queryset(relation, repo_version) + return instance.get_hierarchy_related_queryset(relation) + + +class ConceptChildrenView(ConceptHierarchyMixin, ConceptBaseView, ListWithHeadersMixin): is_page_size_capped = True is_searchable = False # a search would list the repo's concepts, not this concept's hierarchy serializer_class = ConceptChildrenSerializer @@ -617,7 +639,7 @@ def get_queryset(self): raise Http404() self.check_object_permissions(self.request, instance) - return get_viewable_concepts(instance.child_concept_queryset(), self.request) + return get_viewable_concepts(self.get_hierarchy_queryset(instance, 'child_concepts'), self.request) def filter_queryset(self, queryset=None): # annotated here, not in get_queryset, to keep it out of CSV exports return Concept.annotate_has_children(super().filter_queryset(queryset)) @@ -626,7 +648,7 @@ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) -class ConceptParentsView(ConceptBaseView, ListWithHeadersMixin): +class ConceptParentsView(ConceptHierarchyMixin, ConceptBaseView, ListWithHeadersMixin): is_page_size_capped = True is_searchable = False # a search would list the repo's concepts, not this concept's hierarchy serializer_class = ConceptParentsSerializer @@ -641,7 +663,7 @@ def get_queryset(self): raise Http404() self.check_object_permissions(self.request, instance) - return get_viewable_concepts(instance.parent_concept_queryset(), self.request) + return get_viewable_concepts(self.get_hierarchy_queryset(instance, 'parent_concepts'), self.request) def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) diff --git a/core/importers/constants.py b/core/importers/constants.py index 7df02df53..426f567c9 100644 --- a/core/importers/constants.py +++ b/core/importers/constants.py @@ -2,3 +2,6 @@ INVALID_UPDATE_IF_EXISTS = "update_if_exists must be either 'true' or 'false'" INVALID_INDEX = "index must be either 'true' or 'false'" NO_CONTENT_TO_IMPORT = 'No content to import' +INVALID_SEED_FROM_IMPORT = "'seed_from_import' must be 'true' or 'false'." +SEED_FROM_IMPORT_IMPORT_TYPE = 'seed_from_import is not supported for npm imports.' +SEED_FROM_IMPORT_ENDPOINT = 'seed_from_import is not supported by this endpoint.' diff --git a/core/importers/importer.py b/core/importers/importer.py index f118ba985..4c42d53f1 100644 --- a/core/importers/importer.py +++ b/core/importers/importer.py @@ -19,6 +19,7 @@ from packaging.version import Version from pydantic import BaseModel, computed_field, PrivateAttr +from django.core.exceptions import ValidationError as DjangoValidationError from django.utils import timezone from pydash import get from rest_framework.exceptions import ValidationError @@ -26,12 +27,14 @@ from core import settings from core.common.serializers import IdentifierSerializer from core.common.tasks import bulk_import_subtask, bulk_import_subtask_empty, bulk_import_queue +from core.concepts.models import Concept +from core.sources.constants import ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION from core.common.tasks import import_finisher from core.code_systems.converter import CodeSystemConverter from core.common.utils import get_export_service from core.importers.models import SourceImporter, SourceVersionImporter, ConceptImporter, OrganizationImporter, \ CollectionImporter, CollectionVersionImporter, MappingImporter, ReferenceImporter, ImportIndexer, CREATED, \ - UPDATED, FAILED, DELETED, NOT_FOUND, PERMISSION_DENIED, UNCHANGED, should_index_import + UPDATED, FAILED, DELETED, NOT_FOUND, PERMISSION_DENIED, UNCHANGED, should_index_import, IsolatedVersionCommit from core.orgs.models import Organization from core.sources.models import Source from core.users.models import UserProfile @@ -156,6 +159,8 @@ def summary(self) -> ImportTaskSummary: # pylint: disable=too-many-branches results = [child.result] for result in results: + if isinstance(result, dict): + continue summary.processed += 1 if result == CREATED: summary.created += 1 @@ -214,11 +219,14 @@ class Importer: owner: str import_type: str = 'default' index: bool | None = None # None: whether the import is small enough (should_index_import) + isolated_version: bool = False MIN_BATCH_SIZE: int = 50 IMPORT_CACHE: str = "import_cache/" # pylint: disable=too-many-arguments - def __init__(self, task_id, path, username, owner_type, owner, import_type='default', index=None): + def __init__( # pylint: disable=too-many-arguments + self, task_id, path, username, owner_type, owner, import_type='default', index=None, + isolated_version=False): super().__init__() self.task_id = task_id self.path = path @@ -227,6 +235,26 @@ def __init__(self, task_id, path, username, owner_type, owner, import_type='defa self.owner = owner self.import_type = import_type self.index = index + self.isolated_version = isolated_version + self.version_lines = [] + + def validate_versioning(self, resources, resource_types): + if not self.isolated_version: + return resource_types + try: + if sum(get(resources, 'Source Version', {}).values()) != 1: + raise ValidationError(ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION) + IsolatedVersionCommit( + self.version_lines[0], UserProfile.objects.filter(username=self.username).first(), True).preflight() + except DjangoValidationError as ex: + raise ValidationError(ex.message_dict) from ex + return self.get_isolated_version_resource_types(resource_types) + + @staticmethod + def get_isolated_version_resource_types(resource_types): + resource_types = [_type for _type in resource_types if _type != 'Source Version'] + resource_types.insert(resource_types.index('Mapping') + 1, 'Source Version') + return resource_types def is_npm_import(self) -> bool: return self.import_type == 'npm' @@ -271,6 +299,7 @@ def run(self): # pylint: disable=too-many-locals dependencies = [] self.prepare_resources(self.path, resource_types, dependencies, [], resources) + resource_types = self.validate_versioning(resources, resource_types) self.index = should_index_import(self.index, sum(sum(files.values()) for files in resources.values())) tasks = self.prepare_tasks(resource_types, dependencies, resources) if tasks: @@ -443,15 +472,17 @@ def schedule_tasks(self, tasks): group_queue = [] for task in tasks: group_tasks = [] + previous_subtask_ids = list(subtask_ids) for group_task in task: # TODO: create 2 queues for new bulk import subtasks: bulk_import_subtask and bulk_import_subtask_root subtask_id = uuid() subtask_ids.append(subtask_id) - group_tasks.append(bulk_import_subtask.si(group_task['path'], group_task['username'], - group_task['owner_type'], group_task['owner'], - group_task['resource_type'], group_task['files'], - self.index) - .set(task_id=subtask_id)) + args = (group_task['path'], group_task['username'], group_task['owner_type'], group_task['owner'], + group_task['resource_type'], group_task['files'], self.index) + if self.isolated_version: + is_version = group_task['resource_type'] == 'Source Version' + args = (*args, True, is_version, *((previous_subtask_ids, self.task_id) if is_version else ())) + group_tasks.append(bulk_import_subtask.si(*args).set(task_id=subtask_id)) if len(group_tasks) == 1: # Prevent celery from converting group to a single task group_tasks.append(bulk_import_subtask_empty.si()) @@ -480,7 +511,9 @@ def categorize_resources(self, json_file, path, file_path, resource_types, resou try: parser = ijson.parse(json_file, multiple_values=True, allow_comments=True) + line = None # top-level scalar fields of the current resource, to keep its Source Version lines for prefix, event, value in parser: + line = self.collect_version_line(line, prefix, event, value) # Expect {"resourceType": ""}{"resourceType": ""} or {"type": ""}{"type": ""} if event == 'string' and (prefix in {'resourceType', 'type'}): # Categorize files based on resourceType @@ -498,6 +531,20 @@ def categorize_resources(self, json_file, path, file_path, resource_types, resou except JSONError as json_error: raise JSONError(f'Failed to process {path}/{file_path}') from json_error + def collect_version_line(self, line, prefix, event, value): + if not prefix: + if event == 'start_map': + return {} + if event == 'end_map' and get(line, 'type') == 'Source Version': + self.version_lines.append(line) + return line if event == 'map_key' else None + if line is not None and '.' not in prefix: + if event in ('string', 'number', 'boolean', 'null'): + line[prefix] = value + elif event in ('start_map', 'start_array'): + line[prefix] = {} if event == 'start_map' else [] + return line + class ImportRequest: path: str @@ -514,8 +561,10 @@ class ResourceImporter: converters = [CodeSystemConverter] result_type = [CREATED, UPDATED, FAILED, DELETED, NOT_FOUND, PERMISSION_DENIED, UNCHANGED] - def __init__(self, indexer=None): + def __init__(self, indexer=None, isolated=False): self.indexer = indexer # collects the concepts and mappings imported with _index=False + self.isolated = isolated + self.importer = None @staticmethod def get_resource_types(): @@ -543,7 +592,10 @@ def import_resource(self, resource, username, owner_type, owner): for resource_importer in self.resource_importers: if resource_importer.can_handle(resource): user_profile = UserProfile.objects.get(username=username) - importer = resource_importer(resource, user_profile, True) + is_content = resource_importer in (ConceptImporter, MappingImporter) + importer = resource_importer( + resource, user_profile, True, **({'isolated': self.isolated} if is_content else {})) + self.importer = importer result = importer.run() if self.indexer: self.indexer.add(get(importer, 'instance')) @@ -663,7 +715,9 @@ class ImporterSubtask: indexer: ImportIndexer # pylint: disable=too-many-arguments - def __init__(self, path, username, owner_type, owner, resource_type, files, index=True): + def __init__( + self, path, username, owner_type, owner, resource_type, files, index=True, isolated=False, + isolated_version=False, previous_subtask_ids=None, import_task_id=None): super().__init__() self.path = path self.username = username @@ -672,8 +726,14 @@ def __init__(self, path, username, owner_type, owner, resource_type, files, inde self.resource_type = resource_type self.files = files self.indexer = ImportIndexer(index) - - def run(self): + self.isolated = isolated + self.isolated_version = isolated_version + self.previous_subtask_ids = previous_subtask_ids or [] + self.import_task_id = import_task_id + self.seen = {'concepts': set(), 'mappings': set()} + self.hierarchy_map = {} + + def run(self): # pylint: disable=too-many-branches results = [] try: @@ -688,6 +748,8 @@ def run(self): ImporterUtils.fetch_to_file(remote_file, temp) is_zipped, is_tarred = ImporterUtils.is_zipped_or_tarred(temp) + if self.isolated_version: + self.collect_hierarchy_map(temp, is_zipped, is_tarred) if is_zipped: self.import_zip(temp, results) @@ -712,8 +774,47 @@ def run(self): results.extend([str(ex)] * (results_count - len(results))) self.indexer.finish() + if self.isolated and not self.isolated_version: + results.append({'seen': {key: sorted(value) for key, value in self.seen.items()}}) return results + def collect_hierarchy_map(self, temp, is_zipped, is_tarred): + def collect(json_file): + for item in ijson.items(json_file, '', multiple_values=True, allow_comments=True, use_float=True): + if isinstance(item, dict) and item.get('type') == 'Concept': + self.hierarchy_map.update(Concept.get_import_hierarchy_map([item], include_parentless=True)) + + temp.seek(0) + if is_zipped: + with ZipFile(temp) as package: + for info in package.infolist(): + if info.filename.endswith('.json') and info.file_size: + with package.open(info) as json_file: + collect(json_file) + elif is_tarred: + with tarfile.open(fileobj=temp, mode='r') as package: + for member in package.getmembers(): + if member.name.endswith('.json') and member.size: + with package.extractfile(member) as json_file: + collect(json_file) + else: + collect(temp) + temp.seek(0) + + def commit_isolated_version(self, version_line): + commit = IsolatedVersionCommit( + version_line, UserProfile.objects.get(username=self.username), True, hierarchy_map=self.hierarchy_map, + import_task_id=self.import_task_id) + for results in self.iter_previous_results(): + commit.add_subtask_results(results) + return commit.run() + + def iter_previous_results(self): + """Each earlier subtask's results in turn, so only one is held at a time.""" + for task_id in self.previous_subtask_ids: + result = AsyncResult(task_id).result + yield result if isinstance(result, list) else [result] + def import_zip(self, temp, results): with ZipFile(temp) as package: for file in self.files: @@ -768,6 +869,11 @@ def import_files(self, temp, results): except Exception as ex: self.add_exception_to_results(file, start_index, end_index, count, ex, results) + def add_seen(self, importer, result): + versioned_object_id = importer.get_seen_versioned_object_id(result) if importer else None + if versioned_object_id: + self.seen['concepts' if isinstance(importer, ConceptImporter) else 'mappings'].add(versioned_object_id) + @staticmethod def add_exception_to_results(file, start_index, end_index, count, ex, results): error = f"Failed to process {file.get('filepath', '')}({start_index}:{end_index}) " \ @@ -784,7 +890,7 @@ def import_resource(self, json_file, filepath, start_index, end_index): # pylin count = None results = [] - for resource in ijson.items(parse, '', multiple_values=True, allow_comments=True): + for resource in ijson.items(parse, '', multiple_values=True, allow_comments=True, use_float=True): if resource.get('__action', None) == 'DELETE': continue @@ -799,10 +905,16 @@ def import_resource(self, json_file, filepath, start_index, end_index): # pylin resource['owner_type'] = self.owner_type if 'owner' not in resource: resource['owner'] = self.owner - result = ResourceImporter(self.indexer).import_resource( - resource, self.username, self.owner_type, self.owner) + if self.isolated_version and self.resource_type == 'Source Version': + resource_importer = None + result = self.commit_isolated_version(resource) + else: + resource_importer = ResourceImporter(self.indexer, self.isolated) + result = resource_importer.import_resource( + resource, self.username, self.owner_type, self.owner) if isinstance(result, int): results.append(result) + self.add_seen(get(resource_importer, 'importer'), result) else: results.append(f'{error} due to: {result}') except Exception as e: @@ -819,7 +931,7 @@ def move_to_start_index(self, json_file, start_index): json_file.seek(0) # position at the beginning of file if start_index != 0: index = 0 - parse_events = ijson.parse(json_file, multiple_values=True, allow_comments=True) + parse_events = ijson.parse(json_file, multiple_values=True, allow_comments=True, use_float=True) for prefix, event, value in parse_events: if event == 'string' and prefix in ('resourceType', 'type') and value == self.resource_type: index += 1 diff --git a/core/importers/models.py b/core/importers/models.py index ab0dfae19..3ea397e4d 100644 --- a/core/importers/models.py +++ b/core/importers/models.py @@ -7,6 +7,7 @@ from celery.utils.log import get_task_logger from django.conf import settings from django.core.exceptions import ValidationError +from django.db import transaction from django.db.models import F from ocldev.oclfleximporter import OclFlexImporter from pydash import compact, get @@ -16,11 +17,13 @@ from core.common import ERRBIT_LOGGER from core.common.constants import HEAD, ALL from core.common.tasks import bulk_import_parts_inline, delete_organization, batch_index_resources, \ - post_import_update_resource_counts, make_hierarchy, index_concepts_mapped_codes + post_import_update_resource_counts, index_concepts_mapped_codes from core.common.utils import drop_version, is_url_encoded_string, encode_string, to_parent_uri, chunks from core.concepts.models import Concept from core.mappings.models import Mapping from core.orgs.models import Organization +from core.sources.constants import ISOLATED_METADATA_FIELDS, ISOLATED_VERSION_CONTENT_FAILED, \ + ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_NO_EDIT_ACCESS, SEEDED_FROM_IMPORT from core.sources.models import Source from core.tasks.models import Task from core.users.models import UserProfile @@ -109,13 +112,14 @@ class BaseResourceImporter: mandatory_fields = set() allowed_fields = [] - def __init__(self, data, user, update_if_exists=False, cache=None): + def __init__(self, data, user, update_if_exists=False, cache=None, isolated=False): # pylint: disable=too-many-arguments self.user = user self.data = data self.update_if_exists = update_if_exists self.queryset = None self.index_resources = False self.cache = cache if cache is not None else {} + self.isolated = isolated @classmethod def can_handle(cls, obj): @@ -192,6 +196,17 @@ def run(self): def process(self): raise NotImplementedError() + def track_isolated_result(self, result): + if self.isolated and result in (UPDATED, UNCHANGED) and get(self, 'instance.versioned_object_id'): + if not self.instance.versioned_object.is_active: + self.instance.restore_to_head() + return result + + def get_seen_versioned_object_id(self, result): + if self.isolated and result in (CREATED, UPDATED, UNCHANGED, DELETED): + return get(self, 'instance.versioned_object_id') + return None + def retire_resource(self, resource): """ Retires a concept or mapping and keeps the version the retire saved as the instance, marked by that save with @@ -309,7 +324,10 @@ def delete(self): class SourceVersionImporter(BaseResourceImporter): mandatory_fields = {"id"} - allowed_fields = ["id", "external_id", "description", "released"] + allowed_fields = [ + "id", "released", "name", "default_locale", "supported_locales", "extras", + *ISOLATED_METADATA_FIELDS + ] @staticmethod def get_resource_type(): @@ -331,15 +349,122 @@ def parse(self): self.data['version'] = self.data.pop('id') self.data['mnemonic'] = source self.data[owner_type] = owner + supported_locales = self.data.get('supported_locales') + if isinstance(supported_locales, str): + self.data['supported_locales'] = supported_locales.split(',') + + def __init__( # pylint: disable=too-many-arguments + self, data, user, update_if_exists=False, cache=None, isolated_version=False, import_task_id=None): + super().__init__(data, user, update_if_exists, cache=cache) + self.isolated_version = isolated_version + self.import_task_id = import_task_id def process(self): source = Source(**self.data) + if self.isolated_version: + source.seeded_from = {'type': SEEDED_FROM_IMPORT, 'task': self.import_task_id} + source._metadata_fields = list(self.data.keys()) # pylint: disable=protected-access if source.has_parent_edit_access(self.user): errors = Source.persist_new_version(source, self.user) return errors or CREATED return PERMISSION_DENIED +class IsolatedVersionRollback(Exception): + def __init__(self, result): + super().__init__(result) + self.result = result + + +class IsolatedVersionCommit: + """ + The last step of an import that seeds a version, shared by every import path. HEAD's hierarchy replacement, the drop + of what the import didn't contain and the version share one transaction. preflight() runs the same checks before + any content imports. + """ + + def __init__( # pylint: disable=too-many-arguments + self, version_line, user, update_if_exists=False, hierarchy_map=None, seen_concept_ids=None, + seen_mapping_ids=None, content_failures=0, import_task_id=None): + self.version_line = version_line + self.import_task_id = import_task_id + self.user = user + self.update_if_exists = update_if_exists + self.hierarchy_map = hierarchy_map or {} + self.seen_concept_ids = set(seen_concept_ids or []) + self.seen_mapping_ids = set(seen_mapping_ids or []) + self.content_failures = content_failures + + def add_seen(self, seen): + self.seen_concept_ids.update(get(seen, 'concepts') or []) + self.seen_mapping_ids.update(get(seen, 'mappings') or []) + + def add_runner_result(self, result): + """Folds in one BulkImportInline part's result, so the parts are read once and not kept.""" + self.add_seen(get(result, 'seen')) + self.content_failures += sum(len(get(result, f'json.{key}') or []) for key in BulkImportInline.FAILURE_KEYS) + + def add_failed_part(self): + self.content_failures += 1 + + def add_subtask_results(self, results): + """Folds in one archive subtask's results: a status per resource, and a dict of the ids it saw.""" + for result in results: + if isinstance(result, dict): + self.add_seen(get(result, 'seen')) + elif result not in (CREATED, UPDATED, UNCHANGED, DELETED): + self.content_failures += 1 + + def get_head(self): + owner_type = (self.version_line.get('owner_type', '') or '').lower() + owner_filter = 'user__username' if owner_type in ['user', 'users'] else 'organization__mnemonic' + return Source.objects.filter( + **{owner_filter: self.version_line.get('owner')}, mnemonic=self.version_line.get('source'), + version=HEAD).first() + + def get_rejection(self, importer, needs_head=True): + """(True, result) when this version would be rejected. A HEAD the import itself creates isn't there yet.""" + is_clean = importer.clean() + if not is_clean: + return True, is_clean + head = self.get_head() + if (needs_head and not head) or (head and not head.has_edit_access(self.user)): + return True, PERMISSION_DENIED + return False, None + + def preflight(self): + """Runs before any content imports, so a version that would be rejected leaves HEAD untouched.""" + importer = SourceVersionImporter({**self.version_line}, self.user, self.update_if_exists, isolated_version=True) + rejected, result = self.get_rejection(importer, needs_head=False) + if rejected: + raise ValidationError(result if isinstance(result, dict) else {'__all__': [{ + False: ISOLATED_VERSION_LINE_INVALID, None: ISOLATED_VERSION_EXISTS, + PERMISSION_DENIED: ISOLATED_VERSION_NO_EDIT_ACCESS}[result]]}) + + def run(self): + if self.content_failures: + return {'__all__': [ISOLATED_VERSION_CONTENT_FAILED]} + importer = SourceVersionImporter( + {**self.version_line}, self.user, self.update_if_exists, isolated_version=True, + import_task_id=self.import_task_id) + rejected, result = self.get_rejection(importer) + if rejected: + return result + head = self.get_head() + try: + with transaction.atomic(): + Concept.reconcile_import_hierarchy(self.hierarchy_map, self.user, replace_head=True) + head.drop_unseen_children(self.seen_concept_ids, self.seen_mapping_ids) + result = importer.process() + if result != CREATED: + raise IsolatedVersionRollback(result) + except IsolatedVersionRollback as ex: + return ex.result + except ValidationError as ex: + return get(ex, 'message_dict') or {'__all__': ex.messages} + return CREATED + + class CollectionImporter(BaseResourceImporter): mandatory_fields = {'id', 'name', 'owner_type', 'owner'} allowed_fields = [ @@ -442,8 +567,9 @@ class ConceptImporter(BaseResourceImporter): def get_resource_type(): return 'Concept' - def __init__(self, data, user, update_if_exists, skip_hierarchy_tasks=False, cache=None): # pylint: disable=too-many-arguments - super().__init__(data, user, update_if_exists, cache=cache) + def __init__( # pylint: disable=too-many-arguments + self, data, user, update_if_exists, skip_hierarchy_tasks=False, cache=None, isolated=False): + super().__init__(data, user, update_if_exists, cache=cache, isolated=isolated) self.skip_hierarchy_tasks = skip_hierarchy_tasks self.version = False self.instance = None @@ -497,11 +623,11 @@ def process(self): self.instance._index = False # pylint: disable=protected-access errors = Concept.create_new_version_for( instance=self.instance, data=self.data, user=self.user, create_parent_version=False, - add_prev_version_children=False + add_prev_version_children=False, isolated=self.isolated ) if errors and Concept.is_standard_checksum_error(errors): - return UNCHANGED - return errors or UPDATED + return self.track_isolated_result(UNCHANGED) + return errors or self.track_isolated_result(UPDATED) if 'update_comment' in self.data: self.data['comment'] = self.data['update_comment'] @@ -513,7 +639,7 @@ def process(self): data=persist_data, user=self.user, create_parent_version=False) if self.instance.id: - return CREATED + return self.track_isolated_result(CREATED) return self.instance.errors or errors or FAILED return PERMISSION_DENIED @@ -527,7 +653,7 @@ def delete(self): try: if parent.has_edit_access(self.user): self.retire_resource(self.get_queryset().first()) - return DELETED + return self.track_isolated_result(DELETED) return PERMISSION_DENIED except Exception as ex: return {'errors': ex.args} @@ -547,8 +673,8 @@ class MappingImporter(BaseResourceImporter): def get_resource_type(): return 'Mapping' - def __init__(self, data, user, update_if_exists, cache=None): - super().__init__(data, user, update_if_exists, cache=cache) + def __init__(self, data, user, update_if_exists, cache=None, isolated=False): # pylint: disable=too-many-arguments + super().__init__(data, user, update_if_exists, cache=cache, isolated=isolated) self.version = False self.instance = None @@ -668,20 +794,21 @@ def process(self): self.instance._index = False # pylint: disable=protected-access previous_from_concept_id = self.instance.from_concept_id if ( self.instance.from_source_id == self.instance.parent_id) else None - errors = Mapping.create_new_version_for(self.instance, self.data, self.user, cache=self.cache) + errors = Mapping.create_new_version_for( + self.instance, self.data, self.user, cache=self.cache, isolated=self.isolated) if previous_from_concept_id and previous_from_concept_id != self.instance.from_concept_id: # the mapping moved to another from concept, whose mapped codes then need a refresh self.instance.replaced_from_concept_id = previous_from_concept_id if errors and Mapping.is_standard_checksum_error(errors): - return UNCHANGED - return errors or UPDATED + return self.track_isolated_result(UNCHANGED) + return errors or self.track_isolated_result(UPDATED) if 'update_comment' in self.data: self.data['comment'] = self.data['update_comment'] self.data.pop('update_comment') self.instance = Mapping.persist_new( {**self.data, '_counted': None, '_index': False}, self.user, cache=self.cache) if self.instance.id: - return CREATED + return self.track_isolated_result(CREATED) return self.instance.errors or errors or FAILED return PERMISSION_DENIED @@ -695,7 +822,7 @@ def delete(self): try: if parent.has_edit_access(self.user): self.retire_resource(self.get_queryset().first()) - return DELETED + return self.track_isolated_result(DELETED) return PERMISSION_DENIED except Exception as ex: return {'errors': ex.args} @@ -867,11 +994,15 @@ class BulkImportInline(BaseImporter): def __init__( # pylint: disable=too-many-arguments self, content, username, update_if_exists=False, input_list=None, user=None, set_user=True, - self_task_id=None, skip_hierarchy_tasks=False, index=None + self_task_id=None, skip_hierarchy_tasks=False, index=None, isolated_version=False, isolated=False ): super().__init__(content, username, update_if_exists, user, not bool(input_list), set_user) self.self_task_id = self_task_id self.skip_hierarchy_tasks = skip_hierarchy_tasks + self.isolated_version = isolated_version + self.isolated = isolated or isolated_version + self.seen_concept_ids = set() + self.seen_mapping_ids = set() # Lookup cache shared across this run's items (see ConceptImporter/MappingImporter). # It caches misses too (None/False), so it's only safe because a chunk is single-resource-type # in the production parallel path (BulkImportParallelRunner.make_parts splits concepts and @@ -902,10 +1033,31 @@ def __init__( # pylint: disable=too-many-arguments self.last_progress_notified_at = 0 self.elapsed_seconds = 0 self.index = should_index_import(index, self.total) + self.preflight_isolated_version(Source.get_import_version_line(self.input_list, self.isolated_version)) + + def preflight_isolated_version(self, version_line): + if version_line: + IsolatedVersionCommit(version_line, self.user, self.update_if_exists).preflight() def set_task(self): self.task = Task.objects.filter(id=self.self_task_id).first() + FAILURE_KEYS = ('failed', 'exception', 'permission_denied', 'invalid', 'unknown', 'others') + + @property + def content_failures_count(self): + return sum(len(getattr(self, key)) for key in self.FAILURE_KEYS) + + def import_source_version(self, item): + if not self.isolated_version: + return SourceVersionImporter(item, self.user, self.update_if_exists).run() + return IsolatedVersionCommit( + item, self.user, self.update_if_exists, + hierarchy_map=Concept.get_import_hierarchy_map(self.input_list, include_parentless=True), + seen_concept_ids=self.seen_concept_ids, seen_mapping_ids=self.seen_mapping_ids, + content_failures=self.content_failures_count, import_task_id=self.self_task_id + ).run() + def handle_item_import_result(self, result, item): # pylint: disable=too-many-return-statements if result is None: self.exists.append(item) @@ -992,9 +1144,7 @@ def run(self): # pylint: disable=too-many-branches,too-many-statements,too-many ) continue if item_type == 'source version': - self.handle_item_import_result( - SourceVersionImporter(item, self.user, self.update_if_exists).run(), original_item - ) + self.handle_item_import_result(self.import_source_version(item), original_item) continue if item_type == 'collection': collection_importer = CollectionImporter(item, self.user, self.update_if_exists) @@ -1012,10 +1162,11 @@ def run(self): # pylint: disable=too-many-branches,too-many-statements,too-many concept_importer = ConceptImporter( item, self.user, self.update_if_exists, skip_hierarchy_tasks=self.skip_hierarchy_tasks and bool(item.get('id')), - cache=self.cache + cache=self.cache, isolated=self.isolated ) _result = concept_importer.delete() if action == 'delete' else concept_importer.run() indexer.add(concept_importer.instance) + self.seen_concept_ids.update(compact([concept_importer.get_seen_versioned_object_id(_result)])) except Exception as ex: ERRBIT_LOGGER.log(ex) _result = {'__all__': str(ex)} @@ -1023,9 +1174,11 @@ def run(self): # pylint: disable=too-many-branches,too-many-statements,too-many continue if item_type == 'mapping': try: - mapping_importer = MappingImporter(item, self.user, self.update_if_exists, cache=self.cache) + mapping_importer = MappingImporter( + item, self.user, self.update_if_exists, cache=self.cache, isolated=self.isolated) _result = mapping_importer.delete() if action == 'delete' else mapping_importer.run() indexer.add(mapping_importer.instance) + self.seen_mapping_ids.update(compact([mapping_importer.get_seen_versioned_object_id(_result)])) except Exception as ex: ERRBIT_LOGGER.log(ex) _result = {'__all__': str(ex)} @@ -1087,13 +1240,18 @@ def make_result(self): 'detailed_summary': self.detailed_summary, 'report': self.report } + if self.isolated and not self.isolated_version: + self.result['seen'] = {'concepts': sorted(self.seen_concept_ids), 'mappings': sorted(self.seen_mapping_ids)} class BulkImportParallelRunner(BaseImporter): # pragma: no cover def __init__( - self, content, username, update_if_exists, parallel=None, self_task_id=None, index=None + self, content, username, update_if_exists, parallel=None, self_task_id=None, index=None, + isolated_version=False ): # pylint: disable=too-many-arguments super().__init__(content, username, update_if_exists, None, False) + self.isolated_version = isolated_version + self.isolated_version_results = {} self.start_time = time.time() self.self_task_id = self_task_id self.set_task() @@ -1115,6 +1273,9 @@ def __init__( self.populate_input_list() self.total = len(self.input_list) self.index = should_index_import(index, self.total) + version_line = Source.get_import_version_line(self.input_list, self.isolated_version) + if version_line: + IsolatedVersionCommit(version_line, self.user, self.update_if_exists).preflight() self.make_resource_distribution() self.make_parts() self.collect_concept_hierarchy_map() @@ -1166,22 +1327,8 @@ def make_parts(self): prev_line = line def collect_concept_hierarchy_map(self): - for line in self.input_list: - if line.get('type', '').lower() != 'concept': - continue - parent_urls = line.get('parent_concept_urls') or [] - concept_id = line.get('id') - owner = line.get('owner') - source = line.get('source') - if parent_urls and concept_id and owner and source: - owner_type = line.get('owner_type', '').lower() - owner_prefix = 'users' if owner_type in ['user', 'users'] else 'orgs' - # P2: normalize concept_id the same way ConceptImporter.parse() does, - # so the URI matches what was actually persisted in the database. - if not is_url_encoded_string(concept_id): - concept_id = encode_string(concept_id, safe='') - child_uri = f'/{owner_prefix}/{owner}/sources/{source}/concepts/{concept_id}/' - self.concept_hierarchy_map[child_uri] = parent_urls + self.concept_hierarchy_map = Concept.get_import_hierarchy_map( + self.input_list, include_parentless=self.isolated_version) @staticmethod def get_resource_id(resource): @@ -1265,6 +1412,43 @@ def get_overall_tasks_progress(self): def has_hierarchy_reconciliation_step(self): return bool(self.concept_hierarchy_map) + def reconcile_hierarchy(self): + # an import-seeded version's hierarchy is rebuilt only by its commit, inside the version's transaction + if self.isolated_version or self.hierarchy_reconciliation_done or not self.concept_hierarchy_map: + return + user = UserProfile.objects.filter(username=self.username).first() + Concept.reconcile_import_hierarchy(self.concept_hierarchy_map, user) + self.hierarchy_reconciliation_done = True + self.notify_progress() + + def commit_isolated_version(self, version_line): + commit = IsolatedVersionCommit( + version_line, UserProfile.objects.filter(username=self.username).first(), self.update_if_exists, + hierarchy_map=self.concept_hierarchy_map, import_task_id=self.self_task_id) + for task in self.tasks: + try: + task_result = task.result if task.successful() else None + except: # pylint: disable=bare-except + task_result = None + # a failed, lost or expired part saw nothing, so committing would drop its codes + if isinstance(task_result, dict): + commit.add_runner_result(task_result) + else: + commit.add_failed_part() + result = commit.run() + # the commit owns the hierarchy, so a rejected version leaves it untouched + self.hierarchy_reconciliation_done = True + self.isolated_version_results.setdefault(self.get_result_key(result), []).append( + {**version_line, 'errors': result} if isinstance(result, dict) else version_line) + self.notify_progress() + + @staticmethod + def get_result_key(result): + if isinstance(result, dict): + return 'failed' + return {None: 'exists', False: 'invalid', CREATED: 'created', PERMISSION_DENIED: 'permission_denied'}.get( + result, 'others') + def get_total_progress_target(self): return self.total + int(self.has_hierarchy_reconciliation_step()) @@ -1298,6 +1482,9 @@ def run(self): print("***************") while len(self.parts) > 0: part_list = self.parts.popleft() + if part_list and self.isolated_version and get(part_list, '0.type', '').lower() == 'source version': + self.commit_isolated_version(part_list[0]) + part_list = part_list[1:] if part_list: part_type = get(part_list, '0.type', '').lower() if part_type: @@ -1311,33 +1498,7 @@ def run(self): self.resource_wise_time[part_type] += round(time.time() - start_time, 4) self.notify_progress() - if self.concept_hierarchy_map: - # P1: restrict reconciliation to concepts the importing user can actually edit, - # mirroring the has_edit_access guard in ConceptImporter.process(). This excludes - # PERMISSION_DENIED rows and prevents hierarchy changes on sources the user does - # not own, even when those concepts already exist in the database. - user = UserProfile.objects.filter(username=self.username).first() - accessible_uris = set( - concept.uri - for concept in Concept.objects.filter( - uri__in=self.concept_hierarchy_map.keys(), id=F('versioned_object_id') - ).select_related('parent') - if concept.parent.has_edit_access(user) - ) - viewable_parent_uris = set(Concept.get_viewable_parent_uris( - list({uri for uris in self.concept_hierarchy_map.values() for uri in uris}), user)) - inverted = {} - for child_uri, parent_uris in self.concept_hierarchy_map.items(): - if child_uri not in accessible_uris: - continue - for parent_uri in [uri for uri in parent_uris if uri in viewable_parent_uris]: - if parent_uri not in inverted: - inverted[parent_uri] = [] - inverted[parent_uri].append(child_uri) - if inverted: - make_hierarchy(inverted) - self.hierarchy_reconciliation_done = True - self.notify_progress() + self.reconcile_hierarchy() post_import_update_resource_counts.apply_async(queue='default', permanent=False) @@ -1405,6 +1566,9 @@ def json_result(self): except: # pylint: disable=bare-except pass + for key, items in self.isolated_version_results.items(): + total_result[key] += items + total_result['processed'] += len(items) total_result['start_time'] = self.start_time_formatted total_result['elapsed_seconds'] = self.elapsed_seconds total_result['child_resource_time_distribution'] = self.resource_wise_time @@ -1433,7 +1597,7 @@ def queue_tasks(self, part_list, is_child): chunked_lists = [part_list] if has_delete_action else compact( self.chunker_list(part_list, self.parallel, is_child)) jobs = group( - bulk_import_parts_inline.s(_list, self.username, self.update_if_exists, self.index) + bulk_import_parts_inline.s(_list, self.username, self.update_if_exists, self.index, self.isolated_version) for _list in chunked_lists ) group_result = jobs.apply_async(queue='concurrent') diff --git a/core/importers/tests.py b/core/importers/tests.py index b3b6d5593..7c7fbd29b 100644 --- a/core/importers/tests.py +++ b/core/importers/tests.py @@ -29,25 +29,28 @@ from core.collections.tests.factories import OrganizationCollectionFactory from core.common.constants import OPENMRS_VALIDATION_SCHEMA, DEPRECATED_API_HEADER, ACCESS_TYPE_NONE from core.common.tasks import post_import_update_resource_counts, bulk_import_parts_inline, bulk_import_inline, \ - bulk_import, batch_index_resources, bulk_import_parallel_inline, bulk_import_new, index_concepts_mapped_codes + bulk_import, batch_index_resources, bulk_import_parallel_inline, bulk_import_new, index_concepts_mapped_codes, \ + index_dropped_source_children from core.common.tests import OCLAPITestCase, OCLTestCase from core.common.utils import decode_string, startswith_temp_version, get_bulk_import_celery_once_lock_key from core.concepts.documents import ConceptDocument -from core.concepts.models import Concept +from core.concepts.models import Concept, HierarchicalConcepts from core.concepts.tests.factories import ConceptFactory from core.importers.importer import ImporterSubtask, ImportTask, ImportTaskSummary, Importer, ResourceImporter from core.importers.input_parsers import ImportContentParser from core.importers.models import BulkImport, BulkImportInline, BulkImportParallelRunner, \ CREATED, UPDATED, DELETED, PERMISSION_DENIED, UNCHANGED, FAILED, NOT_FOUND, \ BaseImporter, BaseResourceImporter, OrganizationImporter, SourceImporter, SourceVersionImporter, \ - CollectionImporter, CollectionVersionImporter, ConceptImporter, MappingImporter, ReferenceImporter, ImportIndexer + CollectionImporter, CollectionVersionImporter, ConceptImporter, MappingImporter, ReferenceImporter, ImportIndexer, \ + IsolatedVersionCommit from core.importers.views import csv_file_data_to_input_list, ImportRetrieveDestroyMixin from core.mappings.documents import MappingDocument from core.mappings.models import Mapping from core.mappings.tests.factories import MappingFactory from core.orgs.models import Organization from core.orgs.tests.factories import OrganizationFactory -from core.sources.constants import AUTO_ID_SEQUENTIAL, AUTO_ID_UUID +from core.sources.constants import AUTO_ID_SEQUENTIAL, AUTO_ID_UUID, ISOLATED_VERSION_CONTENT_FAILED, \ + ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_NO_EDIT_ACCESS from core.sources.models import Source from core.sources.tests.factories import OrganizationSourceFactory from core.toggles.models import Toggle @@ -3277,7 +3280,7 @@ def group_of(signatures): bulk_import_parts_inline_mock.reset_mock() importer = BulkImportParallelRunner(json.dumps(concept), 'ocladmin', True, None, 'runner-task-id', index) importer.queue_tasks([concept], True) - bulk_import_parts_inline_mock.s.assert_called_once_with([concept], 'ocladmin', True, index) + bulk_import_parts_inline_mock.s.assert_called_once_with([concept], 'ocladmin', True, index, False) def test_celery_once_lock_key_matches_the_task_key(self): """Revoking an import clears its celery_once lock under the key get_bulk_import_celery_once_lock_key rebuilds @@ -3571,9 +3574,9 @@ def test_collect_concept_hierarchy_map_ignores_non_concepts(self): @patch('core.importers.models.post_import_update_resource_counts.apply_async', Mock()) @patch('core.importers.models.BulkImportParallelRunner.wait_till_tasks_alive', Mock()) @patch('core.importers.models.BulkImportParallelRunner.queue_tasks', Mock()) - @patch('core.importers.models.make_hierarchy') - def test_run_calls_make_hierarchy_with_inverted_map(self, make_hierarchy_mock): - """After all chunks complete, make_hierarchy receives the inverted {parent_uri: [child_uris]} map.""" + @patch('core.concepts.models.ImportHierarchy.apply') + def test_run_reconciles_the_hierarchy_once(self, apply_mock): + """After all chunks complete, the hierarchy is applied once, with the child linked to its parent.""" org = OrganizationFactory(mnemonic='TestOrg') source = OrganizationSourceFactory(organization=org, mnemonic='TestSource', version='HEAD') parent = ConceptFactory(parent=source, mnemonic='ParentConcept') @@ -3592,21 +3595,21 @@ def test_run_calls_make_hierarchy_with_inverted_map(self, make_hierarchy_mock): }), ]) - importer = BulkImportParallelRunner(content, 'ocladmin', True) - importer.run() + with patch('core.concepts.models.Concept.get_versioned_objects_by_uri', + wraps=Concept.get_versioned_objects_by_uri) as resolve_mock: + importer = BulkImportParallelRunner(content, 'ocladmin', True) + importer.run() - make_hierarchy_mock.assert_called_once() + apply_mock.assert_called_once_with(False) + resolve_mock.assert_called_once() self.assertTrue(importer.hierarchy_reconciliation_done) - inverted = make_hierarchy_mock.call_args[0][0] - self.assertIn(parent.uri, inverted) - self.assertIn(child.uri, inverted[parent.uri]) @patch('core.importers.models.post_import_update_resource_counts.apply_async', Mock()) @patch('core.importers.models.BulkImportParallelRunner.wait_till_tasks_alive', Mock()) @patch('core.importers.models.BulkImportParallelRunner.queue_tasks', Mock()) - @patch('core.importers.models.make_hierarchy') - def test_run_skips_make_hierarchy_when_no_hierarchy(self, make_hierarchy_mock): - """make_hierarchy is not called when no concept in the import has parent_concept_urls.""" + @patch('core.concepts.models.ImportHierarchy.apply') + def test_run_skips_hierarchy_when_no_hierarchy(self, apply_mock): + """The hierarchy isn't applied when no concept in the import has parent_concept_urls.""" content = '\n'.join([ json.dumps({ "type": "Concept", "id": "StandaloneConcept", @@ -3616,7 +3619,7 @@ def test_run_skips_make_hierarchy_when_no_hierarchy(self, make_hierarchy_mock): importer = BulkImportParallelRunner(content, 'ocladmin', True) importer.run() - make_hierarchy_mock.assert_not_called() + apply_mock.assert_not_called() @patch('core.importers.models.post_import_update_resource_counts.apply_async', Mock()) @patch('core.importers.models.BulkImportParallelRunner.wait_till_tasks_alive', Mock()) @@ -3686,10 +3689,9 @@ def test_run_hierarchy_parent_before_child(self): @patch('core.importers.models.post_import_update_resource_counts.apply_async', Mock()) @patch('core.importers.models.BulkImportParallelRunner.wait_till_tasks_alive', Mock()) @patch('core.importers.models.BulkImportParallelRunner.queue_tasks', Mock()) - @patch('core.importers.models.make_hierarchy') - def test_run_excludes_inaccessible_concepts(self, make_hierarchy_mock): + def test_run_excludes_inaccessible_concepts(self): """ - Concepts from sources the importing user cannot edit must be excluded from make_hierarchy, + Concepts from sources the importing user cannot edit must be excluded from the hierarchy, even when they exist in the database. This prevents hierarchy changes on foreign sources that were denied during import (P1 security fix). """ @@ -3728,17 +3730,9 @@ def test_run_excludes_inaccessible_concepts(self, make_hierarchy_mock): importer = BulkImportParallelRunner(content, importing_user.username, True) importer.run() - make_hierarchy_mock.assert_called_once() - inverted = make_hierarchy_mock.call_args[0][0] - - # OrgA child must be linked to its parent - self.assertIn(parent_a.uri, inverted) - self.assertIn(child_a.uri, inverted[parent_a.uri]) - - # OrgB child must NOT appear — user has no access to SourceB - self.assertNotIn(parent_b.uri, inverted) - all_children = [uri for uris in inverted.values() for uri in uris] - self.assertNotIn(child_b.uri, all_children) + self.assertEqual( + set(child_a.parent_concepts.values_list('id', flat=True)), {parent_a.get_latest_version().id}) + self.assertFalse(child_b.parent_concepts.exists()) class BulkImportViewTest(OCLAPITestCase): @@ -4563,7 +4557,7 @@ def test_bulk_import_parts_inline(self, bulk_import_inline_mock): bulk_import_parts_inline([1, 2], 'username', True) # pylint: disable=no-value-for-parameter bulk_import_inline_mock.assert_called_once_with( content=None, username='username', update_if_exists=True, input_list=[1, 2], - self_task_id=ANY, skip_hierarchy_tasks=True, index=True + self_task_id=ANY, skip_hierarchy_tasks=True, index=True, isolated=False ) bulk_import_inline_mock().run.assert_called_once() @@ -4571,23 +4565,25 @@ def test_bulk_import_parts_inline(self, bulk_import_inline_mock): bulk_import_parts_inline([1, 2], 'username', True, False) # pylint: disable=no-value-for-parameter bulk_import_inline_mock.assert_called_once_with( content=None, username='username', update_if_exists=True, input_list=[1, 2], - self_task_id=ANY, skip_hierarchy_tasks=True, index=False + self_task_id=ANY, skip_hierarchy_tasks=True, index=False, isolated=False ) @patch('core.importers.models.BulkImportInline') def test_bulk_import_inline(self, bulk_import_inline_mock): bulk_import_inline_mock.run = Mock() - bulk_import_inline([1, 2], 'username', True) + bulk_import_inline([1, 2], 'username', True) # pylint: disable=no-value-for-parameter bulk_import_inline_mock.assert_called_once_with( # the import's size decides - content=[1, 2], username='username', update_if_exists=True, index=None + content=[1, 2], username='username', update_if_exists=True, index=None, isolated_version=False, + self_task_id=ANY ) bulk_import_inline_mock().run.assert_called_once() bulk_import_inline_mock.reset_mock() - bulk_import_inline([1, 2], 'username', True, False) + bulk_import_inline([1, 2], 'username', True, False) # pylint: disable=no-value-for-parameter bulk_import_inline_mock.assert_called_once_with( - content=[1, 2], username='username', update_if_exists=True, index=False + content=[1, 2], username='username', update_if_exists=True, index=False, isolated_version=False, + self_task_id=ANY ) @patch('core.importers.models.BulkImportParallelRunner') @@ -4595,7 +4591,7 @@ def test_bulk_import_parallel_inline(self, runner_mock): bulk_import_parallel_inline('content', 'username', True, 2, False) # pylint: disable=no-value-for-parameter runner_mock.assert_called_once_with( content='content', username='username', update_if_exists=True, parallel=2, self_task_id=ANY, - index=False + index=False, isolated_version=False ) runner_mock().run.assert_called_once() @@ -6435,3 +6431,646 @@ def test_deprecated_inline_route_limited_too(self, task_mock): response = self.post(self.preview_user, {'file': self.json_file(600)}, url='/importers/bulk-import-inline/') self.assertEqual(response.status_code, 403) self.assertEqual(response.data['error_code'], 'imports_file_size_limit_reached') + + +LOINC_HEAD_SEED = {'type': 'repo_version', 'url': '/orgs/Regen/sources/LOINC/HEAD/'} + + +@patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) +@patch('core.sources.models.index_source_concepts', Mock(__name__='index_source_concepts')) +@patch('core.importers.models.index_concepts_mapped_codes', Mock()) +@patch('core.importers.models.batch_index_resources', Mock(__name__='batch_index_resources')) +class IsolatedVersionImportTest(OCLTestCase): + def setUp(self): + super().setUp() + self.org = OrganizationFactory(mnemonic='Regen') + self.source_line = { + 'type': 'Source', 'id': 'LOINC', 'name': 'LOINC', 'owner_type': 'Organization', 'owner': 'Regen', + 'default_locale': 'en', 'supported_locales': 'en' + } + + @staticmethod + def concept(mnemonic, parents=None, **kwargs): + return { + 'type': 'Concept', 'id': mnemonic, 'concept_class': 'LOINC', 'datatype': 'N/A', 'owner': 'Regen', + 'owner_type': 'Organization', 'source': 'LOINC', + 'names': [{'name': f'{mnemonic} name', 'locale': 'en', 'locale_preferred': True}], + 'parent_concept_urls': [f'/orgs/Regen/sources/LOINC/concepts/{parent}/' for parent in parents or []], + **kwargs + } + + @staticmethod + def mapping(mnemonic, from_concept, to_concept): + return { + 'type': 'Mapping', 'id': mnemonic, 'map_type': 'SAME-AS', 'owner': 'Regen', 'owner_type': 'Organization', + 'source': 'LOINC', 'from_concept_url': f'/orgs/Regen/sources/LOINC/concepts/{from_concept}/', + 'to_concept_url': f'/orgs/Regen/sources/LOINC/concepts/{to_concept}/' + } + + @staticmethod + def version(version, **kwargs): + return { + 'type': 'Source Version', 'id': version, 'source': 'LOINC', 'owner': 'Regen', 'owner_type': 'Organization', + 'description': f'LOINC {version}', 'released': True, **kwargs + } + + def run_import(self, lines, isolated_version=True, self_task_id=None): + importer = BulkImportInline( + '\n'.join(json.dumps(line) for line in [self.source_line, *lines]), 'ocladmin', True, + isolated_version=isolated_version, self_task_id=self_task_id) + with self.captureOnCommitCallbacks(execute=True): + importer.run() + return importer + + @staticmethod + def members(version): + return set(Source.objects.get(mnemonic='LOINC', version=version).concepts.values_list('mnemonic', flat=True)) + + def test_isolated_import_drops_unseen_concepts(self): + self.run_import([self.concept('A'), self.concept('B', extras={'x': 1}), self.version('v1')]) + importer = self.run_import([self.concept('B'), self.concept('C'), self.version('v2')]) + + self.assertEqual(len(importer.failed), 0) + self.assertEqual(self.members('v1'), {'A', 'B'}) + self.assertEqual(self.members('v2'), {'B', 'C'}) + self.assertEqual( + Source.objects.get(mnemonic='LOINC', version='v2').seeded_from, {'type': 'import', 'task': None}) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + self.assertEqual(head.seeded_from, {'type': 'repo_version', 'url': '/orgs/Regen/sources/LOINC/v2/'}) + self.assertEqual(set(head.concepts.filter( + id=F('versioned_object_id'), is_active=True).values_list('mnemonic', flat=True)), {'B', 'C'}) + concept_a = Concept.objects.get(mnemonic='A', id=F('versioned_object_id')) + self.assertFalse(concept_a.is_active) + self.assertTrue(concept_a.get_latest_version().is_latest_version) + self.assertTrue(concept_a.get_latest_version().sources.filter(version='v1').exists()) + self.assertEqual(Concept.objects.get(mnemonic='B', is_latest_version=True).extras, {}) + self.assertEqual(head.active_concepts, 2) + + def test_isolated_import_drops_and_revives_mappings(self): + concepts = [self.concept('A'), self.concept('B')] + self.run_import([*concepts, self.mapping('M1', 'A', 'B'), self.mapping('M2', 'B', 'A'), self.version('v1')]) + self.run_import([*concepts, self.mapping('M1', 'A', 'B'), self.version('v2')]) + self.run_import([*concepts, self.mapping('M1', 'A', 'B'), self.mapping('M2', 'B', 'A'), self.version('v3')]) + + def mapping_members(version): + return set(Source.objects.get(mnemonic='LOINC', version=version).mappings.values_list( + 'mnemonic', flat=True)) + + self.assertEqual(mapping_members('v1'), {'M1', 'M2'}) + self.assertEqual(mapping_members('v2'), {'M1'}) + self.assertEqual(mapping_members('v3'), {'M1', 'M2'}) + self.assertTrue(Mapping.objects.get(mnemonic='M2', id=F('versioned_object_id')).is_active) + + def test_isolated_import_revives_dropped_concept(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + concept_a_v1 = Concept.objects.get(mnemonic='A', is_latest_version=True) + self.run_import([self.concept('B'), self.version('v2')]) + self.run_import([self.concept('A'), self.concept('B'), self.version('v3')]) + + self.assertEqual(self.members('v3'), {'A', 'B'}) + self.assertEqual(self.members('v2'), {'B'}) + concept_a = Concept.objects.get(mnemonic='A', id=F('versioned_object_id')) + self.assertTrue(concept_a.is_active) + self.assertEqual(concept_a.id, concept_a_v1.versioned_object_id) + self.assertTrue(Source.objects.get(mnemonic='LOINC', version='v1').concepts.filter( + id=concept_a_v1.id).exists()) + + def test_isolated_import_moves_child_without_leaking_old_parent(self): + self.run_import([ + self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P1']), self.version('v1')]) + self.run_import([ + self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P2']), self.version('v2')]) + + concept = Concept.objects.get(mnemonic='C', id=F('versioned_object_id')) + v1 = Source.objects.get(mnemonic='LOINC', version='v1') + v2 = Source.objects.get(mnemonic='LOINC', version='v2') + self.assertEqual( + set(concept.get_version_hierarchy_queryset('parent_concepts', v1).values_list('mnemonic', flat=True)), + {'P1'}) + self.assertEqual( + set(concept.get_version_hierarchy_queryset('parent_concepts', v2).values_list('mnemonic', flat=True)), + {'P2'}) + parent_one = Concept.objects.get(mnemonic='P1', id=F('versioned_object_id')) + self.assertFalse(parent_one.get_version_hierarchy_queryset('child_concepts', v2).exists()) + self.assertEqual( + set(parent_one.get_version_hierarchy_queryset('child_concepts', v1).values_list('mnemonic', flat=True)), + {'C'}) + self.assertEqual(concept.parent_concept_urls, ['/orgs/Regen/sources/LOINC/concepts/P2/']) + + def test_isolated_import_fails_when_hierarchy_root_is_dropped(self): + self.run_import([self.concept('ROOT'), self.concept('A', parents=['ROOT']), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + head.hierarchy_root = Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')) + head.save() + + importer = self.run_import([self.concept('A'), self.version('v2')]) + + self.assertEqual(len(importer.failed), 1) + self.assertIn('hierarchy_root', importer.failed[0]['errors']) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) + self.assertTrue(Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')).is_active) + + def test_isolated_import_skips_version_when_content_fails(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + invalid = self.concept('C') + invalid.pop('concept_class') + + importer = self.run_import([self.concept('A'), invalid, self.version('v2')]) + + self.assertEqual(len(importer.invalid), 1) + self.assertEqual(importer.failed[0]['errors'], {'__all__': [ISOLATED_VERSION_CONTENT_FAILED]}) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) + self.assertTrue(Concept.objects.get(mnemonic='B', id=F('versioned_object_id')).is_active) + + def test_isolated_import_needs_one_source_version_after_content(self): + for lines in ( + [self.concept('A')], + [self.concept('A'), self.version('v1'), self.version('v2')], + [self.version('v1'), self.concept('A')], + ): + with self.assertRaises(DjangoValidationError): + self.run_import(lines) + + def test_carry_forward_import_keeps_unseen_concepts(self): + self.run_import([self.concept('A'), self.concept('B', extras={'x': 1}), self.version('v1')], False) + self.run_import([self.concept('B'), self.version('v2')], False) + + self.assertEqual(self.members('v2'), {'A', 'B'}) + self.assertEqual(Concept.objects.get(mnemonic='B', is_latest_version=True).extras, {'x': 1}) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v2').seeded_from, LOINC_HEAD_SEED) + self.assertIsNone(Source.objects.get(mnemonic='LOINC', version='HEAD').seeded_from) + + @staticmethod + def head_concepts(): + return set(Source.objects.get(mnemonic='LOINC', version='HEAD').concepts.filter( + id=F('versioned_object_id'), is_active=True).values_list('mnemonic', flat=True)) + + @staticmethod + def head_parents(mnemonic): + return set(HierarchicalConcepts.objects.filter( + child__mnemonic=mnemonic, child_id=F('child__versioned_object_id')).values_list( + 'parent__mnemonic', flat=True)) + + @patch('core.sources.models.Source.batch_index') + def test_rejected_version_leaves_head_unchanged(self, batch_index_mock): + self.run_import([ + self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P1']), self.concept('A'), + self.version('v1')]) + batch_index_mock.reset_mock() + + with patch('core.sources.models.Source.persist_new_version', return_value={'version': ['Not saved']}): + importer = self.run_import([ + self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P2']), self.version('v2')]) + + self.assertEqual(importer.failed[0]['errors'], {'version': ['Not saved']}) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) + self.assertEqual(self.head_concepts(), {'P1', 'P2', 'C', 'A'}) + batch_index_mock.assert_not_called() + + def test_existing_version_changes_nothing(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + + with self.assertRaises(DjangoValidationError) as context: + self.run_import([self.concept('B'), self.concept('NEW'), self.version('v1')]) + + self.assertEqual(context.exception.message_dict, {'__all__': [ISOLATED_VERSION_EXISTS]}) + self.assertFalse(Concept.objects.filter(mnemonic='NEW').exists()) + self.assertEqual(self.head_concepts(), {'A', 'B'}) + + def test_preflight_rejects_a_version_before_content_imports(self): + self.run_import([self.concept('A'), self.version('v1')]) + user = UserProfileFactory() + for line, message in ( + ({'source': 'LOINC', 'owner': 'Regen', 'owner_type': 'Organization'}, ISOLATED_VERSION_LINE_INVALID), + (self.version('v2'), ISOLATED_VERSION_NO_EDIT_ACCESS), + ): + with self.assertRaises(DjangoValidationError) as context: + IsolatedVersionCommit(line, user).preflight() + self.assertEqual(context.exception.message_dict, {'__all__': [message]}) + self.assertIsNone(IsolatedVersionCommit( + {**self.version('v2'), 'source': 'NEW'}, UserProfile.objects.get(username='ocladmin')).preflight()) + + @patch('core.sources.models.Source.batch_index', side_effect=Exception('ES down')) + def test_failed_search_update_does_not_undo_a_committed_version(self, batch_index_mock): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + + importer = self.run_import([self.concept('B'), self.version('v2')]) + + self.assertTrue(batch_index_mock.called) + self.assertEqual(len(importer.created), 1) + self.assertEqual(self.members('v2'), {'B'}) + self.assertEqual(self.head_concepts(), {'B'}) + + @patch('core.sources.models.index_dropped_source_children.apply_async') + def test_dropped_codes_are_repaired_by_a_queued_task(self, apply_async_mock): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + dropped = Concept.objects.get(mnemonic='A', id=F('versioned_object_id')) + kept = Concept.objects.get(mnemonic='B', id=F('versioned_object_id')) + + with override_settings(TEST_MODE=False), self.captureOnCommitCallbacks(execute=True): + head.drop_unseen_children([kept.id], []) + + task = Task.objects.get(name=index_dropped_source_children.name) + args = [head.id, [dropped.id, dropped.get_latest_version().id], [], True] + self.assertEqual(task.args, args) + apply_async_mock.assert_called_once_with(args, task_id=task.id, queue='indexing', persist_args=True) + + @patch('core.sources.models.DROPPED_CHILDREN_CHUNK_SIZE', 2) + @patch('core.sources.models.index_dropped_source_children.apply_async') + def test_dropped_codes_repair_is_queued_in_chunks(self, apply_async_mock): + self.run_import([self.concept('A'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + + with override_settings(TEST_MODE=False): + tasks = head.queue_index_dropped_children([1, 2, 3, 4, 5], [6]) + + self.assertEqual([task.args for task in tasks], [ + [head.id, [1, 2], [6], True], [head.id, [3, 4], [], False], [head.id, [5], [], False]]) + self.assertEqual(apply_async_mock.call_count, 3) + + @patch('core.sources.models.index_dropped_source_children.apply_async', side_effect=Exception('broker down')) + def test_dropped_codes_repair_that_cannot_be_queued_is_a_failed_task_that_reruns(self, _): + self.run_import([self.concept('A'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + + with override_settings(TEST_MODE=False): + task, = head.queue_index_dropped_children([1], [2]) + + task.refresh_from_db() + self.assertEqual(task.state, 'FAILURE') + self.assertEqual(task.error_message, 'broker down') + with patch('core.common.tasks.index_dropped_source_children.apply_async') as rerun_mock, \ + patch.object(Task, 'clear_celery_once_lock'): + task.rerun() + rerun_mock.assert_called_once_with( + args=[head.id, [1], [2], True], kwargs={}, queue='indexing', task_id=task.id, persist_args=True) + + def test_dropped_codes_repair_task_retries_and_reindexes(self): + self.assertEqual(index_dropped_source_children.max_retries, 5) + self.assertIn(Exception, index_dropped_source_children.autoretry_for) + self.run_import([self.concept('A'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + + with patch('core.sources.models.Source.index_dropped_children') as index_mock: + index_dropped_source_children(head.id, [1], [2]) + index_dropped_source_children(head.id, [3], [], False) + index_dropped_source_children(0, [1], [2]) + + self.assertEqual(index_mock.call_args_list, [call([1], [2], True), call([3], [], False)]) + + def test_failed_or_missing_parallel_part_blocks_the_version(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + content = '\n'.join(json.dumps(line) for line in [self.source_line, self.concept('B'), self.version('v2')]) + runner = BulkImportParallelRunner(content, 'ocladmin', True, None, 'task-id', isolated_version=True) + done = Mock(result={'seen': {'concepts': [Concept.objects.get(mnemonic='B', id=F('versioned_object_id')).id]}, + 'json': {}}) + for failed_part in (Mock(result=Exception('worker lost'), successful=Mock(return_value=False)), + Mock(result=None)): + runner.tasks = [done, failed_part] + runner.commit_isolated_version(self.version('v2')) + + self.assertEqual(len(runner.isolated_version_results['failed']), 2) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) + self.assertEqual(self.head_concepts(), {'A', 'B'}) + + def test_hierarchy_root_drop_rolls_back_the_hierarchy(self): + self.run_import([ + self.concept('ROOT'), self.concept('P1'), self.concept('C', parents=['P1']), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + head.hierarchy_root = Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')) + head.save() + + importer = self.run_import([self.concept('P1'), self.concept('C'), self.version('v2')]) + + self.assertIn('hierarchy_root', importer.failed[0]['errors']) + self.assertEqual(self.head_concepts(), {'ROOT', 'P1', 'C'}) + self.assertEqual(self.head_parents('C'), {'P1'}) + + def test_commit_rolls_back_the_hierarchy_with_the_version(self): + self.run_import([ + self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P1']), self.version('v1')]) + version_line = self.version('v2') + version_line.pop('type') + prefix = '/orgs/Regen/sources/LOINC/concepts/' + + def commit(): + with self.captureOnCommitCallbacks(execute=True): + return IsolatedVersionCommit( + version_line, UserProfile.objects.get(username='ocladmin'), + hierarchy_map={f'{prefix}C/': [f'{prefix}P2/'], f'{prefix}P1/': [], f'{prefix}P2/': []}, + seen_concept_ids=Concept.objects.filter( + mnemonic__in=['P1', 'P2', 'C'], id=F('versioned_object_id')).values_list('id', flat=True) + ).run() + + with patch('core.sources.models.Source.persist_new_version', return_value={'version': ['Not saved']}): + self.assertEqual(commit(), {'version': ['Not saved']}) + self.assertEqual(self.head_parents('C'), {'P1'}) + + self.assertEqual(commit(), CREATED) + self.assertEqual(self.head_parents('C'), {'P2'}) + + def test_seeded_from_records_the_import_task_and_survives_a_later_head_version(self): + self.run_import([self.concept('A'), self.version('v1')], self_task_id='import-task-id') + self.run_import([self.concept('B'), self.version('v2', versioning_mode='isolated')], False) + + self.assertEqual( + Source.objects.get(mnemonic='LOINC', version='v1').seeded_from, + {'type': 'import', 'task': 'import-task-id'}) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v2').seeded_from, LOINC_HEAD_SEED) + self.assertEqual( + Source.objects.get(mnemonic='LOINC', version='HEAD').seeded_from, + {'type': 'repo_version', 'url': '/orgs/Regen/sources/LOINC/v1/'}) + self.assertEqual(self.members('v2'), {'A', 'B'}) + + def test_plain_version_importer_ignores_versioning_mode(self): + self.run_import([self.concept('A'), self.version('v1')]) + version_line = self.version('v2', versioning_mode='isolated') + version_line.pop('type') + + result = SourceVersionImporter(version_line, UserProfile.objects.get(username='ocladmin')).run() + + self.assertEqual(result, CREATED) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v2').seeded_from, LOINC_HEAD_SEED) + + def test_commit_needs_edit_access_to_head(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + version_line = self.version('v2') + version_line.pop('type') + + result = IsolatedVersionCommit( + version_line, UserProfileFactory(), seen_concept_ids=[ + Concept.objects.get(mnemonic='B', id=F('versioned_object_id')).id]).run() + + self.assertEqual(result, PERMISSION_DENIED) + self.assertEqual(self.head_concepts(), {'A', 'B'}) + + def test_isolated_version_merges_metadata_into_head(self): + self.run_import([self.concept('A'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + head.website = 'https://loinc.org' + head.publisher = 'Old' + head.save() + + self.run_import([self.concept('A'), self.version('v2', publisher='Regenstrief', description='2.82')]) + + head.refresh_from_db() + version = Source.objects.get(mnemonic='LOINC', version='v2') + self.assertEqual(head.publisher, 'Regenstrief') + self.assertEqual(head.description, '2.82') + self.assertEqual(head.website, 'https://loinc.org') + self.assertEqual(version.publisher, 'Regenstrief') + self.assertEqual(version.website, 'https://loinc.org') + self.assertEqual(head.name, 'LOINC') + + +@patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) +@patch('core.sources.models.index_source_concepts', Mock(__name__='index_source_concepts')) +@patch('core.importers.models.index_concepts_mapped_codes', Mock()) +@patch('core.importers.models.batch_index_resources', Mock(__name__='batch_index_resources')) +class IsolatedVersionAPITest(OCLAPITestCase): + def setUp(self): + super().setUp() + self.token = UserProfile.objects.get(username='ocladmin').get_token() + OrganizationFactory(mnemonic='Regen') + + def run_import(self, lines): + with self.captureOnCommitCallbacks(execute=True): + BulkImportInline( + '\n'.join(json.dumps(line) for line in [ + {'type': 'Source', 'id': 'LOINC', 'name': 'LOINC', 'owner_type': 'Organization', 'owner': 'Regen', + 'default_locale': 'en', 'supported_locales': 'en'}, *lines]), + 'ocladmin', True, isolated_version=True).run() + + def test_version_hierarchy_endpoints(self): + concept = IsolatedVersionImportTest.concept + version = IsolatedVersionImportTest.version + self.run_import([concept('P1'), concept('P2'), concept('C', parents=['P1']), version('v1')]) + self.run_import([concept('P1'), concept('P2'), concept('C', parents=['P2']), version('v2')]) + + for repo_version, parent in (('v1', 'P1'), ('v2', 'P2')): + response = self.client.get( + f'/orgs/Regen/sources/LOINC/{repo_version}/concepts/C/parents/', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 200) + self.assertEqual([item['id'] for item in response.data], [parent]) + response = self.client.get( + '/orgs/Regen/sources/LOINC/v2/concepts/P1/children/', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data, []) + response = self.client.get( + '/orgs/Regen/sources/LOINC/concepts/C/parents/', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual([item['id'] for item in response.data], ['P2']) + + def test_version_create_records_head_as_its_seed(self): + self.run_import([IsolatedVersionImportTest.concept('A'), IsolatedVersionImportTest.version('v1')]) + response = self.client.post( + '/orgs/Regen/sources/LOINC/versions/', + {'id': 'v2', 'description': 'v2', 'seeded_from': {'type': 'import', 'task': 'other'}}, + HTTP_AUTHORIZATION='Token ' + self.token, format='json') + self.assertEqual(response.status_code, 201) + self.assertEqual(response.data['seeded_from'], LOINC_HEAD_SEED) + self.assertNotIn('versioning_mode', response.data) + response = self.client.get('/orgs/Regen/sources/LOINC/', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual( + response.data['seeded_from'], {'type': 'repo_version', 'url': '/orgs/Regen/sources/LOINC/v1/'}) + + @patch('core.importers.views.queue_bulk_import') + def test_import_passes_seed_from_import(self, queue_bulk_import_mock): + queue_bulk_import_mock.return_value = Task.new(queue='default', username='ocladmin', name='bulk_import') + response = self.client.post( + '/importers/bulk-import/?update_if_exists=true&seed_from_import=true', {'data': '{"type": "Concept"}'}, + HTTP_AUTHORIZATION='Token ' + self.token, format='json') + self.assertEqual(response.status_code, 202) + self.assertTrue(queue_bulk_import_mock.call_args.kwargs['isolated_version']) + + response = self.client.post( + '/importers/bulk-import/?isolated_version=true', {'data': '{"type": "Concept"}'}, + HTTP_AUTHORIZATION='Token ' + self.token, format='json') + self.assertEqual(response.status_code, 202) + self.assertFalse(queue_bulk_import_mock.call_args.kwargs['isolated_version']) + + response = self.client.post( + '/importers/bulk-import/?seed_from_import=maybe', {'data': '{"type": "Concept"}'}, + HTTP_AUTHORIZATION='Token ' + self.token, format='json') + self.assertEqual(response.status_code, 400) + + response = self.client.post( + '/importers/bulk-import/?seed_from_import=true', {'data': '{}', 'import_type': 'npm'}, + HTTP_AUTHORIZATION='Token ' + self.token, format='json') + self.assertEqual(response.status_code, 400) + + @patch('core.common.tasks.bulk_import') + def test_deprecated_upload_rejects_seed_from_import(self, bulk_import_mock): + response = self.client.post( + '/importers/bulk-import/upload/?seed_from_import=true', + {'file': SimpleUploadedFile('file.json', b'{"type": "Concept"}', 'application/json')}, + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data, {'exception': 'seed_from_import is not supported by this endpoint.'}) + bulk_import_mock.apply_async.assert_not_called() + + def test_hierarchy_endpoints_follow_each_version(self): + concept = IsolatedVersionImportTest.concept + version = IsolatedVersionImportTest.version + self.run_import([concept('P'), concept('A', parents=['P']), concept('B', parents=['P']), version('v1')]) + self.run_import([concept('P'), concept('A', parents=['P']), version('v2')]) + + def get_ids(url): + response = self.client.get(url, HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 200) + return sorted(item['id'] for item in response.data) + + self.assertEqual(get_ids('/orgs/Regen/sources/LOINC/v1/concepts/P/children/'), ['A', 'B']) + self.assertEqual(get_ids('/orgs/Regen/sources/LOINC/v2/concepts/P/children/'), ['A']) + self.assertEqual(get_ids('/orgs/Regen/sources/LOINC/concepts/P/children/'), ['A']) + self.assertEqual(get_ids('/orgs/Regen/sources/LOINC/v1/concepts/B/parents/'), ['P']) + response = self.client.get( + '/orgs/Regen/sources/LOINC/v1/concepts/P/?includeChildConceptURLs=true', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual( + sorted(response.data['child_concept_urls']), + ['/orgs/Regen/sources/LOINC/concepts/A/', '/orgs/Regen/sources/LOINC/concepts/B/']) + + def test_version_detail_keeps_parents_dropped_from_head(self): + concept = IsolatedVersionImportTest.concept + version = IsolatedVersionImportTest.version + self.run_import([concept('P'), concept('C', parents=['P']), version('v1')]) + self.run_import([concept('C'), version('v2')]) + + response = self.client.get( + '/orgs/Regen/sources/LOINC/v1/concepts/C/?includeParentConceptURLs=true', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data['parent_concept_urls'], ['/orgs/Regen/sources/LOINC/concepts/P/']) + response = self.client.get( + '/orgs/Regen/sources/LOINC/concepts/C/?includeParentConceptURLs=true', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.data['parent_concept_urls'], []) + response = self.client.get( + '/orgs/Regen/sources/LOINC/concepts/B/', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 404) + + +@patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) +@patch('core.sources.models.index_source_concepts', Mock(__name__='index_source_concepts')) +@patch('core.importers.models.index_concepts_mapped_codes', Mock()) +@patch('core.importers.models.batch_index_resources', Mock(__name__='batch_index_resources')) +class IsolatedVersionZipImportTest(OCLTestCase): + def setUp(self): + super().setUp() + OrganizationFactory(mnemonic='Regen') + BulkImportInline(json.dumps({ + 'type': 'Source', 'id': 'LOINC', 'name': 'LOINC', 'owner_type': 'Organization', 'owner': 'Regen', + 'default_locale': 'en', 'supported_locales': 'en'}), 'ocladmin', True).run() + + def import_zip(self, concepts, mappings, version): + concept = IsolatedVersionImportTest.concept + directory = tempfile.mkdtemp() + path = os.path.join(directory, 'loinc.zip') + with ZipFile(path, 'w') as package: + package.writestr('concepts.json', '\n'.join(json.dumps(concept(*args)) for args in concepts)) + package.writestr('mappings.json', '\n'.join( + json.dumps(IsolatedVersionImportTest.mapping(*args)) for args in mappings)) + package.writestr('version.json', json.dumps(IsolatedVersionImportTest.version(version))) + results = [] + for resource_type, filepath, count in ( + ('Concept', 'concepts.json', len(concepts)), ('Mapping', 'mappings.json', len(mappings))): + if count: + results += ImporterSubtask( + path, 'ocladmin', 'Organization', 'Regen', resource_type, + [{'filepath': filepath, 'start_index': 0, 'end_index': count}], False, True).run() + with patch.object(ImporterSubtask, 'iter_previous_results', return_value=[results]), \ + self.captureOnCommitCallbacks(execute=True): + return ImporterSubtask( + path, 'ocladmin', 'Organization', 'Regen', 'Source Version', + [{'filepath': 'version.json', 'start_index': 0, 'end_index': 1}], False, True, True, + import_task_id='zip-task-id').run() + + def test_isolated_version_zip_import(self): + self.assertEqual(self.import_zip([('A',), ('B',)], [('M1', 'A', 'B')], 'v1'), [CREATED]) + self.assertEqual(self.import_zip([('B',), ('C', ['B'])], [], 'v2'), [CREATED]) + + self.assertEqual(IsolatedVersionImportTest.members('v1'), {'A', 'B'}) + self.assertEqual(IsolatedVersionImportTest.members('v2'), {'B', 'C'}) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v2').mappings.count(), 0) + self.assertEqual( + Source.objects.get(mnemonic='LOINC', version='v2').seeded_from, {'type': 'import', 'task': 'zip-task-id'}) + self.assertEqual( + Concept.objects.get(mnemonic='C', id=F('versioned_object_id')).parent_concept_urls, + ['/orgs/Regen/sources/LOINC/concepts/B/']) + + def test_isolated_version_zip_import_skips_version_when_content_fails(self): + self.import_zip([('A',), ('B',)], [], 'v1') + with patch.object(ImporterSubtask, 'iter_previous_results', return_value=[[CREATED], ['Failed to import']]): + result = ImporterSubtask( + '/dev/null', 'ocladmin', 'Organization', 'Regen', 'Source Version', [], False, True, True + ).commit_isolated_version(IsolatedVersionImportTest.version('v2')) + self.assertEqual(result, {'__all__': [ISOLATED_VERSION_CONTENT_FAILED]}) + + def test_zip_import_with_numeric_extras(self): + directory = tempfile.mkdtemp() + path = os.path.join(directory, 'loinc.zip') + with ZipFile(path, 'w') as package: + package.writestr('concepts.json', '\n'.join( + json.dumps(IsolatedVersionImportTest.concept(mnemonic, extras={'rank': 1.5, 'order': 2})) + for mnemonic in ('N1', 'N2', 'N3'))) + results = [] + for start_index, end_index in ((0, 1), (1, 3)): + results += ImporterSubtask( + path, 'ocladmin', 'Organization', 'Regen', 'Concept', + [{'filepath': 'concepts.json', 'start_index': start_index, 'end_index': end_index}], False).run() + + self.assertEqual(results, [CREATED, CREATED, CREATED]) + self.assertEqual( + Concept.objects.get(mnemonic='N3', id=F('versioned_object_id')).extras, {'rank': 1.5, 'order': 2}) + + def test_categorize_resources_keeps_only_source_version_lines(self): + importer = Importer('task-id', '/tmp/loinc.zip', 'ocladmin', 'Organization', 'Regen', isolated_version=True) + resources = {} + lines = [ + {'type': 'Source', 'id': 'LOINC', 'name': 'LOINC', 'extras': {'type': 'x'}}, + {**IsolatedVersionImportTest.version('v1'), 'name': 'v1', 'extras': {'a': [1]}}, + ] + importer.categorize_resources( + io.BytesIO('\n'.join(json.dumps(line) for line in lines).encode()), + '/tmp/loinc.zip', 'lines.json', ['Source', 'Source Version'], resources) + + self.assertEqual(importer.version_lines, [{ + **IsolatedVersionImportTest.version('v1'), 'name': 'v1', 'extras': {}}]) + self.assertEqual( + importer.validate_versioning(resources, ['Source', 'Source Version', 'Concept', 'Mapping']), + ['Source', 'Concept', 'Mapping', 'Source Version']) + + def test_validate_versioning_rejects_before_content_imports(self): + self.import_zip([('A',)], [], 'v1') + resources = {'Source Version': {'/tmp/loinc.zip/version.json': 1}} + for line, isolated_version, errors in ( + (IsolatedVersionImportTest.version('v1'), True, {'__all__': [ISOLATED_VERSION_EXISTS]}), + ): + importer = Importer( + 'task-id', '/tmp/loinc.zip', 'ocladmin', 'Organization', 'Regen', isolated_version=isolated_version) + importer.version_lines = [line] + with self.assertRaises(ValidationError) as context: + importer.validate_versioning(resources, ['Source Version', 'Concept', 'Mapping']) + self.assertEqual(context.exception.detail, errors) + + @patch('core.importers.importer.bulk_import_queue') + @patch('core.importers.importer.bulk_import_subtask') + def test_version_subtask_gets_the_import_task_id(self, subtask_mock, _): + importer = Importer('zip-task-id', '/tmp/loinc.zip', 'ocladmin', 'Organization', 'Regen', isolated_version=True) + task = {'path': '/tmp/loinc.zip', 'username': 'ocladmin', 'owner_type': 'Organization', 'owner': 'Regen', + 'files': []} + + _, subtask_ids = importer.schedule_tasks([ + [{**task, 'resource_type': 'Concept'}], [{**task, 'resource_type': 'Source Version'}]]) + + concept_args, version_args = [call_.args for call_ in subtask_mock.si.call_args_list] + self.assertEqual(concept_args[-2:], (True, False)) + self.assertEqual(version_args[-4:], (True, True, [subtask_ids[0]], 'zip-task-id')) + + def test_isolated_version_resource_types(self): + self.assertEqual( + Importer.get_isolated_version_resource_types( + ['Source', 'Source Version', 'Concept', 'Mapping', 'Reference']), + ['Source', 'Concept', 'Mapping', 'Source Version', 'Reference']) diff --git a/core/importers/views.py b/core/importers/views.py index c535b721e..bbcc8b629 100644 --- a/core/importers/views.py +++ b/core/importers/views.py @@ -24,10 +24,11 @@ from core.common.views import BaseAPIView from core.common.tasks import bulk_import_new from core.common.swagger_parameters import update_if_exists_param, task_param, result_param, username_param, \ - file_upload_param, file_url_param, parallel_threads_param, verbose_param, index_param + file_upload_param, file_url_param, parallel_threads_param, verbose_param, index_param, seed_from_import_param from core.common.utils import queue_bulk_import, is_csv_file, get_truthy_values, get_queue_task_names, \ get_export_service -from core.importers.constants import ALREADY_QUEUED, INVALID_UPDATE_IF_EXISTS, NO_CONTENT_TO_IMPORT, INVALID_INDEX +from core.importers.constants import ALREADY_QUEUED, INVALID_UPDATE_IF_EXISTS, NO_CONTENT_TO_IMPORT, INVALID_INDEX, \ + INVALID_SEED_FROM_IMPORT, SEED_FROM_IMPORT_IMPORT_TYPE, SEED_FROM_IMPORT_ENDPOINT from core.importers.importer import Importer, ResourceImporter from core.importers.input_parsers import ImportContentParser from core.importers.limits import ( @@ -58,6 +59,15 @@ def get_index_param(request): return index == 'true', None +def get_seed_from_import_param(request, supported=True): + seed_from_import = request.GET.get('seed_from_import', 'false') + if seed_from_import not in ['true', 'false']: + return None, Response({'exception': INVALID_SEED_FROM_IMPORT}, status=status.HTTP_400_BAD_REQUEST) + if seed_from_import == 'true' and not supported: + return None, Response({'exception': SEED_FROM_IMPORT_ENDPOINT}, status=status.HTTP_400_BAD_REQUEST) + return seed_from_import == 'true', None + + def import_response(request, import_queue, data, threads=None, inline=False, deprecated=False): # pylint: disable=too-many-arguments if not data: return Response({'exception': NO_CONTENT_TO_IMPORT}, status=status.HTTP_400_BAD_REQUEST) @@ -73,13 +83,18 @@ def import_response(request, import_queue, data, threads=None, inline=False, dep ) update_if_exists = update_if_exists == 'true' index, error_response = get_index_param(request) + if error_response: + return error_response + seed_from_import, error_response = get_seed_from_import_param(request, supported=inline) if error_response: return error_response data = data.decode('utf-8') if isinstance(data, bytes) else data task = None try: - task = queue_bulk_import(data, import_queue, username, update_if_exists, threads, inline, index=index) + task = queue_bulk_import( + data, import_queue, username, update_if_exists, threads, inline, index=index, + isolated_version=seed_from_import) task.refresh_from_db() except AlreadyQueued: if task: @@ -180,7 +195,8 @@ def get_parsers(self): @swagger_auto_schema( manual_parameters=[ - update_if_exists_param, index_param, file_url_param, file_upload_param, parallel_threads_param + update_if_exists_param, index_param, seed_from_import_param, file_url_param, file_upload_param, + parallel_threads_param ], deprecated=True ) @@ -259,15 +275,21 @@ def store_upload(file): @swagger_auto_schema( manual_parameters=[ - update_if_exists_param, index_param, file_url_param, file_upload_param, parallel_threads_param + update_if_exists_param, index_param, seed_from_import_param, file_url_param, file_upload_param, + parallel_threads_param ], ) - def post(self, request, import_queue=None): # pylint: disable=too-many-locals + def post(self, request, import_queue=None): # pylint: disable=too-many-locals,too-many-return-statements,too-many-branches check_request_body_size(request) if 'import_type' in request.data: index, error_response = get_index_param(request) if error_response: return error_response + seed_from_import, error_response = get_seed_from_import_param(request) + if error_response: + return error_response + if seed_from_import and request.data.get('import_type', 'npm') == 'npm': + return Response({'exception': SEED_FROM_IMPORT_IMPORT_TYPE}, status=status.HTTP_400_BAD_REQUEST) check_import_payload(request) owner_type = request.data.get('owner_type', 'user') owner = request.data.get('owner', self.request.user.username) @@ -299,7 +321,8 @@ def post(self, request, import_queue=None): # pylint: disable=too-many-locals task = get_queue_task_names(sanitize_import_queue(request.user, import_queue), self.request.user.username) new_task = bulk_import_new.apply_async( (file_url, self.request.user.username, owner_type, owner, - request.data.get('import_type', 'npm'), index), task_id=task.id, queue=task.queue) + request.data.get('import_type', 'npm'), index, *([True] if seed_from_import else [])), + task_id=task.id, queue=task.queue) return Response({ 'task': new_task.id, 'state': new_task.state diff --git a/core/integration_tests/tests_sources.py b/core/integration_tests/tests_sources.py index 0ba04f4d8..ba6e5cb08 100644 --- a/core/integration_tests/tests_sources.py +++ b/core/integration_tests/tests_sources.py @@ -204,7 +204,8 @@ def test_post_201(self): 'jurisdiction', 'purpose', 'copyright', 'content_type', 'supplements', 'supplement_type', 'supplement_global', 'revision_date', 'logo_url', 'text', 'experimental', 'case_sensitive', 'collection_reference', 'hierarchy_meaning', 'compositional', - 'version_needed', 'hierarchy_root_url', 'autoid_concept_mnemonic', 'autoid_mapping_mnemonic', + 'version_needed', 'seeded_from', 'hierarchy_root_url', 'autoid_concept_mnemonic', + 'autoid_mapping_mnemonic', 'autoid_concept_external_id', 'autoid_mapping_external_id', 'autoid_concept_name_external_id', 'autoid_concept_description_external_id', 'autoid_concept_mnemonic_start_from', 'autoid_concept_external_id_start_from', @@ -327,7 +328,8 @@ def test_put_200(self): 'jurisdiction', 'purpose', 'copyright', 'content_type', 'supplements', 'supplement_type', 'supplement_global', 'revision_date', 'logo_url', 'text', 'experimental', 'case_sensitive', 'collection_reference', 'hierarchy_meaning', 'compositional', - 'version_needed', 'hierarchy_root_url', 'autoid_concept_mnemonic', 'autoid_mapping_mnemonic', + 'version_needed', 'seeded_from', 'hierarchy_root_url', 'autoid_concept_mnemonic', + 'autoid_mapping_mnemonic', 'autoid_concept_external_id', 'autoid_mapping_external_id', 'autoid_concept_name_external_id', 'autoid_concept_description_external_id', 'autoid_concept_mnemonic_start_from', 'autoid_concept_external_id_start_from', @@ -2960,6 +2962,29 @@ def test_markdown_output_for_all_verbosity_levels(self): self.assertIn('mapping-target-v1', markdown_output) self.assertIn('mapping-target-v2', markdown_output) + @override_settings(CHANGELOG_ENRICHMENT_MAX_RESOURCES=1) + def test_large_diff_skips_enrichment(self): + data = self._build_changelog_output_fixture() + token = data['source'].created_by.get_token() + + response = self._post_changelog(data['source_v1'], data['source_v2'], token, 4, output='json') + + self.assertEqual(response.status_code, 200) + self.assertTrue(response.data['meta']['enrichment_skipped']) + changed_concept = response.data['concepts']['changed_major']['concept-detailed'] + self.assertEqual(changed_concept['id'], 'concept-detailed') + self.assertIn('display_name', changed_concept) + self.assertNotIn('names', changed_concept) + self.assertNotIn('prev_names', changed_concept) + changed_mapping = response.data['mappings']['changed_major']['mapping-detailed'] + self.assertEqual(changed_mapping['to_concept'], 'mapping-target-v2') + self.assertNotIn('prev_to_concept', changed_mapping) + + response = self._post_changelog(data['source_v1'], data['source_v2'], token, 4, output='markdown') + + self.assertEqual(response.status_code, 200) + self.assertIn('without enrichment', response.data['markdown']) + class SourceVersionsComparisonViewTest(OCLAPITestCase): def test_post_200(self): # pylint: disable=too-many-locals,too-many-statements @@ -3368,6 +3393,10 @@ def test_post_200(self): # pylint: disable=too-many-statements,too-many-locals } ) + @patch('core.common.checksums.ChecksumChangelog.CONCEPTS_BATCH_SIZE', 1) + def test_post_200_in_concept_batches_of_one(self): + self.test_post_200() + class SourceReleaseFlagsTest(OCLAPITestCase): """ diff --git a/core/mappings/models.py b/core/mappings/models.py index a99815b06..4610536bc 100644 --- a/core/mappings/models.py +++ b/core/mappings/models.py @@ -474,16 +474,13 @@ def is_existing_in_parent(self): return self.parent.mappings_set.filter(mnemonic__exact=self.mnemonic).exists() @classmethod - def create_new_version_for(cls, instance, data, user, cache=None): + def create_new_version_for(cls, instance, data, user, cache=None, isolated=False): # pylint: disable=too-many-arguments instance.populate_fields_from_relations(data, cache=cache, user=user) - instance.extras = data.get('extras', instance.extras) - instance.external_id = data.get('external_id', instance.external_id) instance.mnemonic = data.get('mnemonic', instance.mnemonic) instance.map_type = data.get('map_type', instance.map_type) - instance.sort_weight = data.get('sort_weight', instance.sort_weight) instance.comment = data.get('update_comment') or data.get('comment') - instance.retire_reason = data.get('retire_reason', instance.retire_reason) - instance.retired = data.get('retired', instance.retired) + instance.set_version_fields( + data, ('extras', 'external_id', 'sort_weight', 'retire_reason', 'retired'), isolated) return instance.save_as_new_version(user) diff --git a/core/settings.py b/core/settings.py index f3e8de165..b2a403015 100644 --- a/core/settings.py +++ b/core/settings.py @@ -732,6 +732,8 @@ def get_set_from_env(name): LIST_QUERY_TIMEOUT_MS = int(os.environ.get('LIST_QUERY_TIMEOUT_MS', 30000)) # Largest page a concept, mapping or reference list serves, so one page stays a short request LIST_MAX_LIMIT = int(os.environ.get('LIST_MAX_LIMIT', 100)) +# Above this many new, removed or changed concepts and mappings, a changelog skips names, descriptions and prev_* +CHANGELOG_ENRICHMENT_MAX_RESOURCES = int(os.environ.get('CHANGELOG_ENRICHMENT_MAX_RESOURCES', 50000)) ANALYTICS_API = os.environ.get('ANALYTICS_API', 'http://host.docker.internal:8002') if ANALYTICS_API: diff --git a/core/sources/constants.py b/core/sources/constants.py index 69d0b86c5..14040a458 100644 --- a/core/sources/constants.py +++ b/core/sources/constants.py @@ -11,6 +11,22 @@ CONTENT_TYPE_SUPPLEMENT = 'supplement' SUPPLEMENTS_REQUIRED = 'A supplement must name the code system it supplements.' SUPPLEMENTS_FORMAT = 'Enter the canonical URL of the code system, optionally followed by |version.' +SEEDED_FROM_REPO_VERSION = 'repo_version' +SEEDED_FROM_IMPORT = 'import' +ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION = \ + 'A seed_from_import import needs exactly one Source Version line, after its concepts and mappings.' +ISOLATED_VERSION_CONTENT_FAILED = 'Not created: some of the version content failed to import.' +ISOLATED_VERSION_LINE_INVALID = 'The Source Version line needs an id.' +ISOLATED_VERSION_EXISTS = 'This Source Version already exists.' +ISOLATED_VERSION_NO_EDIT_ACCESS = 'You need edit access to the source to import a version into it.' +HIERARCHY_ROOT_CANNOT_BE_DROPPED = 'Hierarchy Root must be present in a version seeded from an import.' +ISOLATED_METADATA_FIELDS = ( + 'description', 'full_name', 'website', 'external_id', 'canonical_url', 'identifier', 'contact', 'jurisdiction', + 'publisher', 'purpose', 'copyright', 'revision_date', 'text', 'experimental', 'source_type', 'content_type', + 'supplements', 'supplement_type', 'supplement_global', + 'collection_reference', 'hierarchy_meaning', 'case_sensitive', 'compositional', 'version_needed', +) +ISOLATED_REQUIRED_METADATA_FIELDS = ('name', 'default_locale', 'supported_locales') HIERARCHY_MEANINGS = ( ('grouped-by', 'grouped-by'), ('is-a', 'is-a'), @@ -26,3 +42,5 @@ LOCALE_EXTERNAL_AUTO_ID_CHOICES = ( (AUTO_ID_UUID, 'UUID'), ) + +DROPPED_CHILDREN_CHUNK_SIZE = 5000 diff --git a/core/sources/migrations/0048_source_versioning_mode.py b/core/sources/migrations/0048_source_versioning_mode.py new file mode 100644 index 000000000..876e163d3 --- /dev/null +++ b/core/sources/migrations/0048_source_versioning_mode.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.17 on 2026-11-05 13:45 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('sources', '0047_source_supplements'), + ] + + operations = [ + migrations.AddField( + model_name='source', + name='versioning_mode', + field=models.CharField(blank=True, choices=[('carry_forward', 'Carry Forward'), ('isolated', 'Isolated')], default='carry_forward', max_length=20, null=True), + ), + ] diff --git a/core/sources/migrations/0049_source_seeded_from.py b/core/sources/migrations/0049_source_seeded_from.py new file mode 100644 index 000000000..04008ae8d --- /dev/null +++ b/core/sources/migrations/0049_source_seeded_from.py @@ -0,0 +1,54 @@ +from django.db import migrations, models + + +def backfill_seeded_from(apps, schema_editor): # pylint: disable=unused-argument + """ + Every version made so far was seeded from HEAD, except those an import seeded. HEAD records the latest version an + import seeded, if any. + """ + Source = apps.get_model('sources', 'Source') + to_update = [] + imported_by_head = {} + versions = Source.objects.exclude(version='HEAD').order_by('created_at').only( + 'id', 'version', 'versioning_mode', 'organization_id', 'user_id', 'mnemonic') + for version in versions.iterator(chunk_size=2000): + if version.versioning_mode == 'isolated': + version.seeded_from = {'type': 'import', 'task': None} + imported_by_head[(version.organization_id, version.user_id, version.mnemonic)] = version.version + else: + version.seeded_from = {'type': 'repo_version', 'url': None} + to_update.append(version) + heads = { + (head.organization_id, head.user_id, head.mnemonic): head + for head in Source.objects.filter(version='HEAD').only('id', 'uri', 'organization_id', 'user_id', 'mnemonic') + } + for version in to_update: + head = heads.get((version.organization_id, version.user_id, version.mnemonic)) + if version.seeded_from['type'] == 'repo_version': + version.seeded_from['url'] = f'{head.uri}HEAD/' if head and head.uri else None + for key, version in imported_by_head.items(): + head = heads.get(key) + if head and head.uri: + head.seeded_from = {'type': 'repo_version', 'url': f'{head.uri}{version}/'} + to_update.append(head) + Source.objects.bulk_update(to_update, ['seeded_from'], batch_size=2000) + + +class Migration(migrations.Migration): + + dependencies = [ + ('sources', '0048_source_versioning_mode'), + ] + + operations = [ + migrations.AddField( + model_name='source', + name='seeded_from', + field=models.JSONField(blank=True, null=True), + ), + migrations.RunPython(backfill_seeded_from, migrations.RunPython.noop), + migrations.RemoveField( + model_name='source', + name='versioning_mode', + ), + ] diff --git a/core/sources/models.py b/core/sources/models.py index 4fb6d4754..dac059dcd 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -1,6 +1,7 @@ import uuid from collections import OrderedDict +from celery.states import FAILURE from celery_once import AlreadyQueued from dirtyfields import DirtyFieldsMixin from django.conf import settings @@ -9,20 +10,23 @@ from django.db import models, transaction from django.db.models import UniqueConstraint, F, Max, Count from django.db.models.functions import Cast +from django.utils import timezone from pydash import get, compact from core.common.checksums import VersionCompareMixin -from core.common.constants import HEAD +from core.common.constants import HEAD, VERSION_UNCOPYABLE_EXTRAS from core.common.fields import URIField from core.common.models import ConceptContainerModel from core.common.tasks import update_mappings_source, index_source_concepts, index_source_mappings, \ - sync_source_concept_vectors, index_source_public_access -from core.common.utils import split_canonical, to_camel_case + sync_source_concept_vectors, index_source_public_access, index_dropped_source_children +from core.common.utils import split_canonical, to_camel_case, chunks from core.common.validators import validate_non_negative -from core.concepts.models import ConceptName, Concept +from core.concepts.models import ConceptName, Concept, HierarchicalConcepts from core.services.storages.postgres import PostgresQL from core.sources.constants import SOURCE_TYPE, SOURCE_VERSION_TYPE, HIERARCHY_ROOT_MUST_BELONG_TO_SAME_SOURCE, \ HIERARCHY_MEANINGS, AUTO_ID_CHOICES, AUTO_ID_SEQUENTIAL, AUTO_ID_UUID, LOCALE_EXTERNAL_AUTO_ID_CHOICES, \ + SEEDED_FROM_REPO_VERSION, SEEDED_FROM_IMPORT, ISOLATED_METADATA_FIELDS, ISOLATED_REQUIRED_METADATA_FIELDS, \ + HIERARCHY_ROOT_CANNOT_BE_DROPPED, ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION, DROPPED_CHILDREN_CHUNK_SIZE, \ CONTENT_TYPE_SUPPLEMENT, SUPPLEMENTS_REQUIRED, SUPPLEMENTS_FORMAT, SEED_MEMBERS_WRITTEN, SEED_RELEASE_INDEXED, \ SEED_STAGE from core.tasks.models import Task @@ -115,6 +119,8 @@ class Meta: compositional = models.BooleanField(null=True, blank=True, default=None) version_needed = models.BooleanField(null=True, blank=True, default=None) hierarchy_root = models.ForeignKey('concepts.Concept', null=True, blank=True, on_delete=models.SET_NULL) + # what a version was seeded from, recorded once at creation; on HEAD, what an import last re-seeded it from + seeded_from = models.JSONField(null=True, blank=True) # auto-id autoid_concept_mnemonic = models.CharField(null=True, blank=True, choices=AUTO_ID_CHOICES, max_length=10) autoid_concept_external_id = models.CharField(null=True, blank=True, choices=AUTO_ID_CHOICES, max_length=10) @@ -240,6 +246,109 @@ def update_version_data(self, head): self.compositional = head.compositional self.version_needed = head.version_needed + @property + def is_seeded_from_import(self): + return get(self, 'seeded_from.type') == SEEDED_FROM_IMPORT + + def get_version_url(self, version): + return f'{self.uri}{version}/' + + def apply_version_metadata_to_head(self, head): + if not self.is_seeded_from_import: + self.seeded_from = {'type': SEEDED_FROM_REPO_VERSION, 'url': head.get_version_url(HEAD)} + return + head.seeded_from = {'type': SEEDED_FROM_REPO_VERSION, 'url': head.get_version_url(self.version)} + fields = [field for field in get(self, '_metadata_fields') or [] if field in ISOLATED_METADATA_FIELDS] + for field in fields: + setattr(head, field, getattr(self, field)) + for field in ISOLATED_REQUIRED_METADATA_FIELDS: + if field in (get(self, '_metadata_fields') or []) and getattr(self, field): + setattr(head, field, getattr(self, field)) + if 'extras' in (get(self, '_metadata_fields') or []): + head.extras = { + **{key: value for key, value in (head.extras or {}).items() if key in VERSION_UNCOPYABLE_EXTRAS}, + **(self.extras or {}) + } + head.save() + + def queue_index_dropped_children(self, concept_ids, mapping_ids): + """ + Queues the repair of dropped codes in chunks, each a retried Task with its arguments saved so it can be rerun. + The first chunk also recounts HEAD. A chunk that can't be queued is left as a failed Task. + """ + if get(settings, 'TEST_MODE'): + self.index_dropped_children(concept_ids, mapping_ids) + return [] + concept_chunks = list(chunks(concept_ids, DROPPED_CHILDREN_CHUNK_SIZE)) + mapping_chunks = list(chunks(mapping_ids, DROPPED_CHILDREN_CHUNK_SIZE)) + tasks = [] + for index in range(max(len(concept_chunks), len(mapping_chunks), 1)): + args = [ + self.id, concept_chunks[index] if index < len(concept_chunks) else [], + mapping_chunks[index] if index < len(mapping_chunks) else [], index == 0 + ] + task = Task.new(queue='indexing', user=self.updated_by, name=index_dropped_source_children.name, + args=args) + try: + index_dropped_source_children.apply_async(args, task_id=task.id, queue='indexing', persist_args=True) + except Exception as ex: # pylint: disable=broad-except + task.state = FAILURE + task.finished_at = timezone.now() + task.record_exception(ex) + tasks.append(task) + return tasks + + def index_dropped_children(self, concept_ids, mapping_ids, recount=True): + from core.concepts.documents import ConceptDocument + from core.mappings.documents import MappingDocument + from core.mappings.models import Mapping + for model, document, ids in ((Concept, ConceptDocument, concept_ids), (Mapping, MappingDocument, mapping_ids)): + for chunk in chunks(ids, DROPPED_CHILDREN_CHUNK_SIZE): + self.batch_index(model.objects.filter(id__in=chunk), document) + if recount: + self.update_children_counts(sync=True) + + def drop_unseen_children(self, seen_concept_ids, seen_mapping_ids): + from core.mappings.models import Mapping + to_index = {Concept: [], Mapping: []} + with transaction.atomic(): + Source.objects.select_for_update().get(id=self.id) + concept_ids = set(self.concepts_set.filter( + id=F('versioned_object_id'), is_active=True).values_list('id', flat=True)) - set(seen_concept_ids) + mapping_ids = set(self.mappings_set.filter( + id=F('versioned_object_id'), is_active=True).values_list('id', flat=True)) - set(seen_mapping_ids) + if self.hierarchy_root_id and Concept.objects.filter( + id=self.hierarchy_root_id, versioned_object_id__in=concept_ids).exists(): + raise ValidationError({'hierarchy_root': [HIERARCHY_ROOT_CANNOT_BE_DROPPED]}) + for model, ids in ((Concept, concept_ids), (Mapping, mapping_ids)): + for chunk in chunks(sorted(ids), 5000): + latest_ids = list(model.objects.filter( + versioned_object_id__in=chunk, is_latest_version=True).values_list('id', flat=True)) + model.objects.filter(id__in=chunk).update(is_active=False) + model.sources.through.objects.filter( + 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() + to_index[model] += [*chunk, *latest_ids] + + if to_index[Concept] or to_index[Mapping]: + # registered robustly so a failure to queue can't stop the version's seeding + transaction.on_commit( + lambda: self.queue_index_dropped_children(to_index[Concept], to_index[Mapping]), robust=True) + return {'concepts': len(concept_ids), 'mappings': len(mapping_ids)} + + @staticmethod + def get_import_version_line(input_list, seed_from_import): + """Checks the whole import before anything runs. A seed_from_import import gets its one version line back.""" + if not seed_from_import: + return None + types = [(line.get('type', '') or '').lower() for line in input_list] + version_indexes = [index for index, _type in enumerate(types) if _type == 'source version'] + content_indexes = [index for index, _type in enumerate(types) if _type in ('concept', 'mapping')] + if len(version_indexes) != 1 or (content_indexes and content_indexes[-1] > version_indexes[0]): + raise ValidationError(ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION) + return input_list[version_indexes[0]] + def get_concept_name_locales(self): return ConceptName.objects.filter(concept__in=self.get_active_concepts()) diff --git a/core/sources/serializers.py b/core/sources/serializers.py index 8abf71dd1..feb7133a8 100644 --- a/core/sources/serializers.py +++ b/core/sources/serializers.py @@ -271,6 +271,7 @@ class SourceCreateSerializer(SourceCreateOrUpdateSerializer): hierarchy_meaning = CharField(required=False, allow_null=True, allow_blank=True) collection_reference = CharField(required=False, allow_null=True, allow_blank=True) hierarchy_root_url = CharField(allow_null=True, allow_blank=True, required=False) + seeded_from = JSONField(read_only=True) def validate(self, attrs): # create/create_version consume the raw payload (not validated_data), so DRF's boolean @@ -436,7 +437,7 @@ class Meta: 'content_type', 'supplements', 'supplement_type', 'supplement_global', 'revision_date', 'logo_url', 'summary', 'text', 'client_configs', 'experimental', 'case_sensitive', 'collection_reference', 'hierarchy_meaning', 'compositional', - 'version_needed', 'hierarchy_root_url', 'hierarchy_root', 'meta', + 'version_needed', 'hierarchy_root_url', 'hierarchy_root', 'meta', 'seeded_from', 'autoid_concept_mnemonic', 'autoid_concept_external_id', 'autoid_concept_name_external_id', 'autoid_concept_description_external_id', 'autoid_mapping_mnemonic', 'autoid_mapping_external_id', @@ -532,6 +533,7 @@ class Meta: 'content_type', 'supplements', 'supplement_type', 'supplement_global', 'revision_date', 'summary', 'text', 'meta', 'experimental', 'case_sensitive', 'collection_reference', 'hierarchy_meaning', 'compositional', 'version_needed', 'hierarchy_root_url', 'checksums', 'states', 'tasks', 'properties', 'filters', + 'seeded_from', 'match_algorithms', 'external_exports', 'verification' ) + AbstractRepoResourcesSerializer.Meta.fields read_only_fields = ('verification',) From 254d5b246a2b979ad0e50c6e50923aca5d5cf8db Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 19 Nov 2026 10:16:08 +0530 Subject: [PATCH 2/8] OpenConceptLab/ocl_online#655 | Seeding imports refuse a large drop unless allowed, report what they drop, check content targets, link the hierarchy only on commit and take version defaults from HEAD --- core/common/tasks.py | 8 +- core/concepts/models.py | 24 ++++-- core/concepts/serializers.py | 6 +- core/concepts/views.py | 10 ++- core/importers/importer.py | 6 +- core/importers/models.py | 85 ++++++++++++++++----- core/importers/tests.py | 140 ++++++++++++++++++++++++++++++++++- core/settings.py | 4 + core/sources/constants.py | 7 ++ core/sources/models.py | 21 +++++- 10 files changed, 272 insertions(+), 39 deletions(-) diff --git a/core/common/tasks.py b/core/common/tasks.py index 5adea3897..503036e49 100644 --- a/core/common/tasks.py +++ b/core/common/tasks.py @@ -542,8 +542,7 @@ def process_hierarchy_for_new_concept(concept_id, initial_version_id, parent_con acks_late=True, reject_on_worker_lost=True ) def process_hierarchy_for_concept_version( - latest_version_id, prev_version_id, parent_concept_uris, create_parent_version, - create_removed_parent_versions=True, update_head=True): + latest_version_id, prev_version_id, parent_concept_uris, create_parent_version): """ Executed when a new concept version is created with new, updated or existing hierarchy 1. Associates parent concepts to the latest concept version. @@ -563,10 +562,9 @@ def process_hierarchy_for_concept_version( uri__in=parent_concept_uris) if parent_concept_uris else Concept.objects.none() latest_version._parent_concepts = parent_concepts # pylint: disable=protected-access latest_version.set_parent_concepts_from_uris(create_parent_version) - if update_head: - latest_version.versioned_object.parent_concepts.set(latest_version.parent_concepts.all()) + latest_version.versioned_object.parent_concepts.set(latest_version.parent_concepts.all()) - if prev_version and create_removed_parent_versions: + if prev_version: removed_parent_urls = [ url for url in old_parents if url not in list(latest_version.parent_concept_urls) ] diff --git a/core/concepts/models.py b/core/concepts/models.py index 85730dd77..662d4340a 100644 --- a/core/concepts/models.py +++ b/core/concepts/models.py @@ -1276,10 +1276,10 @@ def _process_prev_latest_version_hierarchy(self, prev_latest, add_prev_version_c task.apply_async((prev_latest.id, self.id), queue='concurrent', permanent=False) def _process_latest_version_hierarchy(self, prev_latest, parent_concept_uris=None, create_parent_version=True): + if get(self, '_isolated'): # a seeding import links the hierarchy when it commits the version + return task = process_hierarchy_for_concept_version args = (self.id, get(prev_latest, 'id'), parent_concept_uris, create_parent_version) - if get(self, '_isolated'): - args = (*args, False, False) if get(settings, 'TEST_MODE', False): task(*args) else: @@ -1399,8 +1399,14 @@ def get_viewable(queryset, user): return queryset.exclude(public_access=ACCESS_TYPE_NONE) return Concept.apply_user_criteria(queryset, user) - def get_viewable_hierarchy_concept_urls(self, relation, user): - """parent_concept_urls or child_concept_urls (`relation`), of concepts in repos `user` can view.""" + def get_viewable_hierarchy_concept_urls(self, relation, user, repo_version=None): + """ + parent_concept_urls or child_concept_urls (`relation`), of concepts in repos `user` can view; with + repo_version, those in that version. + """ + if repo_version: + queryset = self.get_version_hierarchy_queryset(relation, repo_version) + return list(self.get_viewable(queryset, user).values_list('versioned_object__uri', flat=True)) return list(self.get_viewable( self.get_hierarchy_related_queryset(relation), user).values_list('uri', flat=True)) @@ -1443,8 +1449,14 @@ def get_hierarchy_related_queryset(self, relation, versioned=False): return queryset.filter(is_active=True) if self.is_versioned_object else queryset @staticmethod - def annotate_has_children(queryset): - """has_children for each row as part of the list query, by the same rules as the has_children property.""" + def annotate_has_children(queryset, repo_version=None): + """ + has_children for each row as part of the list query, by the same rules as the has_children property; with + repo_version, whether the row has children in that version. + """ + if repo_version: + return queryset.annotate(has_children_annotated=Exists(repo_version.concepts.filter( + parent_concepts__versioned_object_id=OuterRef('versioned_object_id')))) own = HierarchicalConcepts.objects.filter(parent_id=OuterRef('id')) of_head = HierarchicalConcepts.objects.filter(parent_id=OuterRef('versioned_object_id')) newest_latest_version = Concept.objects.filter( diff --git a/core/concepts/serializers.py b/core/concepts/serializers.py index 78929fb99..e079dfdf9 100644 --- a/core/concepts/serializers.py +++ b/core/concepts/serializers.py @@ -804,7 +804,8 @@ def __init__(self, *args, **kwargs): def get_children(self, obj): if self.include_child_concepts: - return obj.get_viewable_hierarchy_concept_urls('child_concepts', get(self, 'context.request.user')) + return obj.get_viewable_hierarchy_concept_urls( + 'child_concepts', get(self, 'context.request.user'), get(self, 'context.repo_version')) return None @@ -835,5 +836,6 @@ def __init__(self, *args, **kwargs): def get_parents(self, obj): if self.include_parent_concepts: - return obj.get_viewable_hierarchy_concept_urls('parent_concepts', get(self, 'context.request.user')) + return obj.get_viewable_hierarchy_concept_urls( + 'parent_concepts', get(self, 'context.request.user'), get(self, 'context.repo_version')) return None diff --git a/core/concepts/views.py b/core/concepts/views.py index 70c1b218f..42b1ac61e 100644 --- a/core/concepts/views.py +++ b/core/concepts/views.py @@ -605,6 +605,11 @@ def get_clone_to_source(self): class ConceptHierarchyMixin: def get_source_version(self): """The source version named in the URL, or None for HEAD and collection URLs.""" + if '_source_version' not in self.__dict__: + self._source_version = self.find_source_version() + return self._source_version + + def find_source_version(self): source, version = self.kwargs.get('source'), self.kwargs.get('version') if not source or not version or version == HEAD: return None @@ -617,6 +622,9 @@ def get_source_version(self): return Source.find_latest_released_version_by({**filters, 'mnemonic': source}) return Source.get_version(source, version, filters) + def get_serializer_context(self): + return {**super().get_serializer_context(), 'repo_version': self.get_source_version()} + def get_hierarchy_queryset(self, instance, relation): repo_version = self.get_source_version() if repo_version: @@ -642,7 +650,7 @@ def get_queryset(self): return get_viewable_concepts(self.get_hierarchy_queryset(instance, 'child_concepts'), self.request) def filter_queryset(self, queryset=None): # annotated here, not in get_queryset, to keep it out of CSV exports - return Concept.annotate_has_children(super().filter_queryset(queryset)) + return Concept.annotate_has_children(super().filter_queryset(queryset), self.get_source_version()) def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) diff --git a/core/importers/importer.py b/core/importers/importer.py index 4c42d53f1..b7e328dff 100644 --- a/core/importers/importer.py +++ b/core/importers/importer.py @@ -237,6 +237,7 @@ def __init__( # pylint: disable=too-many-arguments self.index = index self.isolated_version = isolated_version self.version_lines = [] + self.content_targets = set() def validate_versioning(self, resources, resource_types): if not self.isolated_version: @@ -244,10 +245,11 @@ def validate_versioning(self, resources, resource_types): try: if sum(get(resources, 'Source Version', {}).values()) != 1: raise ValidationError(ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION) + Source.validate_import_targets(self.version_lines[0], self.content_targets) IsolatedVersionCommit( self.version_lines[0], UserProfile.objects.filter(username=self.username).first(), True).preflight() except DjangoValidationError as ex: - raise ValidationError(ex.message_dict) from ex + raise ValidationError(ex.message_dict if hasattr(ex, 'error_dict') else ex.messages) from ex return self.get_isolated_version_resource_types(resource_types) @staticmethod @@ -537,6 +539,8 @@ def collect_version_line(self, line, prefix, event, value): return {} if event == 'end_map' and get(line, 'type') == 'Source Version': self.version_lines.append(line) + elif event == 'end_map' and get(line, 'type') in ('Concept', 'Mapping') and self.isolated_version: + self.content_targets.add(Source.get_import_target(line)) return line if event == 'map_key' else None if line is not None and '.' not in prefix: if event in ('string', 'number', 'boolean', 'null'): diff --git a/core/importers/models.py b/core/importers/models.py index 3ea397e4d..e6c740104 100644 --- a/core/importers/models.py +++ b/core/importers/models.py @@ -23,7 +23,8 @@ from core.mappings.models import Mapping from core.orgs.models import Organization from core.sources.constants import ISOLATED_METADATA_FIELDS, ISOLATED_VERSION_CONTENT_FAILED, \ - ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_NO_EDIT_ACCESS, SEEDED_FROM_IMPORT + ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_NO_EDIT_ACCESS, SEEDED_FROM_IMPORT, \ + ISOLATED_VERSION_LARGE_DROP, ALLOW_LARGE_DROP from core.sources.models import Source from core.tasks.models import Task from core.users.models import UserProfile @@ -196,8 +197,9 @@ def run(self): def process(self): raise NotImplementedError() - def track_isolated_result(self, result): - if self.isolated and result in (UPDATED, UNCHANGED) and get(self, 'instance.versioned_object_id'): + def track_result(self, result): + """A code dropped from HEAD that any import updates, or sends unchanged, is back in HEAD.""" + if result in (UPDATED, UNCHANGED) and get(self, 'instance.versioned_object_id'): if not self.instance.versioned_object.is_active: self.instance.restore_to_head() return result @@ -325,7 +327,7 @@ def delete(self): class SourceVersionImporter(BaseResourceImporter): mandatory_fields = {"id"} allowed_fields = [ - "id", "released", "name", "default_locale", "supported_locales", "extras", + "id", "released", "name", "default_locale", "supported_locales", "extras", "match_algorithms", *ISOLATED_METADATA_FIELDS ] @@ -361,6 +363,7 @@ def __init__( # pylint: disable=too-many-arguments def process(self): source = Source(**self.data) + self.set_head_defaults(source) if self.isolated_version: source.seeded_from = {'type': SEEDED_FROM_IMPORT, 'task': self.import_task_id} source._metadata_fields = list(self.data.keys()) # pylint: disable=protected-access @@ -370,6 +373,18 @@ def process(self): return PERMISSION_DENIED + def set_head_defaults(self, source): + """What the line leaves out comes from HEAD, as for POST .../versions/.""" + head = source.head + if not head: + return + for field in ('meta', 'properties', 'filters'): + if field not in self.data: + setattr(source, field, getattr(head, field)) + if 'match_algorithms' not in self.data: + source.match_algorithms = head.get_match_algorithms_for_new_version() + + class IsolatedVersionRollback(Exception): def __init__(self, result): super().__init__(result) @@ -386,7 +401,9 @@ class IsolatedVersionCommit: def __init__( # pylint: disable=too-many-arguments self, version_line, user, update_if_exists=False, hierarchy_map=None, seen_concept_ids=None, seen_mapping_ids=None, content_failures=0, import_task_id=None): - self.version_line = version_line + self.version_line = {key: value for key, value in version_line.items() if key != ALLOW_LARGE_DROP} + self.allow_large_drop = version_line.get(ALLOW_LARGE_DROP) in (True, 'true') + self.dropped = None self.import_task_id = import_task_id self.user = user self.update_if_exists = update_if_exists @@ -454,7 +471,9 @@ def run(self): try: with transaction.atomic(): Concept.reconcile_import_hierarchy(self.hierarchy_map, self.user, replace_head=True) - head.drop_unseen_children(self.seen_concept_ids, self.seen_mapping_ids) + self.dropped = head.drop_unseen_children(self.seen_concept_ids, self.seen_mapping_ids) + if self.is_large_drop(): + raise IsolatedVersionRollback({'__all__': [ISOLATED_VERSION_LARGE_DROP.format(**self.dropped)]}) result = importer.process() if result != CREATED: raise IsolatedVersionRollback(result) @@ -464,6 +483,15 @@ def run(self): return get(ex, 'message_dict') or {'__all__': ex.messages} return CREATED + def is_large_drop(self): + """At least SEED_FROM_IMPORT_LARGE_DROP_MIN of HEAD's codes leave it, and more than its percent of them.""" + if self.allow_large_drop: + return False + dropped = self.dropped['concepts'] + self.dropped['mappings'] + kept = len(self.seen_concept_ids) + len(self.seen_mapping_ids) + return dropped >= settings.SEED_FROM_IMPORT_LARGE_DROP_MIN and \ + dropped * 100 > settings.SEED_FROM_IMPORT_LARGE_DROP_PERCENT * (dropped + kept) + class CollectionImporter(BaseResourceImporter): mandatory_fields = {'id', 'name', 'owner_type', 'owner'} @@ -626,20 +654,20 @@ def process(self): add_prev_version_children=False, isolated=self.isolated ) if errors and Concept.is_standard_checksum_error(errors): - return self.track_isolated_result(UNCHANGED) - return errors or self.track_isolated_result(UPDATED) + return self.track_result(UNCHANGED) + return errors or self.track_result(UPDATED) if 'update_comment' in self.data: self.data['comment'] = self.data['update_comment'] self.data.pop('update_comment') persist_data = {**self.data, '_counted': None, '_index': False} - if self.skip_hierarchy_tasks: + if self.skip_hierarchy_tasks or self.isolated: # a seeding import links them when it commits persist_data['_skip_hierarchy_tasks'] = True self.instance = Concept.persist_new( data=persist_data, user=self.user, create_parent_version=False) if self.instance.id: - return self.track_isolated_result(CREATED) + return self.track_result(CREATED) return self.instance.errors or errors or FAILED return PERMISSION_DENIED @@ -653,7 +681,7 @@ def delete(self): try: if parent.has_edit_access(self.user): self.retire_resource(self.get_queryset().first()) - return self.track_isolated_result(DELETED) + return self.track_result(DELETED) return PERMISSION_DENIED except Exception as ex: return {'errors': ex.args} @@ -800,15 +828,15 @@ def process(self): # the mapping moved to another from concept, whose mapped codes then need a refresh self.instance.replaced_from_concept_id = previous_from_concept_id if errors and Mapping.is_standard_checksum_error(errors): - return self.track_isolated_result(UNCHANGED) - return errors or self.track_isolated_result(UPDATED) + return self.track_result(UNCHANGED) + return errors or self.track_result(UPDATED) if 'update_comment' in self.data: self.data['comment'] = self.data['update_comment'] self.data.pop('update_comment') self.instance = Mapping.persist_new( {**self.data, '_counted': None, '_index': False}, self.user, cache=self.cache) if self.instance.id: - return self.track_isolated_result(CREATED) + return self.track_result(CREATED) return self.instance.errors or errors or FAILED return PERMISSION_DENIED @@ -822,7 +850,7 @@ def delete(self): try: if parent.has_edit_access(self.user): self.retire_resource(self.get_queryset().first()) - return self.track_isolated_result(DELETED) + return self.track_result(DELETED) return PERMISSION_DENIED except Exception as ex: return {'errors': ex.args} @@ -1027,6 +1055,7 @@ def __init__( # pylint: disable=too-many-arguments self.permission_denied = [] self.unchanged = [] self.others = [] + self.dropped = None self.processed = 0 self.total = len(self.input_list) self.start_time = time.time() @@ -1051,12 +1080,15 @@ def content_failures_count(self): def import_source_version(self, item): if not self.isolated_version: return SourceVersionImporter(item, self.user, self.update_if_exists).run() - return IsolatedVersionCommit( + commit = IsolatedVersionCommit( item, self.user, self.update_if_exists, hierarchy_map=Concept.get_import_hierarchy_map(self.input_list, include_parentless=True), seen_concept_ids=self.seen_concept_ids, seen_mapping_ids=self.seen_mapping_ids, content_failures=self.content_failures_count, import_task_id=self.self_task_id - ).run() + ) + result = commit.run() + self.dropped = commit.dropped + return result def handle_item_import_result(self, result, item): # pylint: disable=too-many-return-statements if result is None: @@ -1225,7 +1257,8 @@ def json_result(self): 'unchanged': self.unchanged, 'others': self.others, 'unknown': self.unknown, - 'elapsed_seconds': self.elapsed_seconds + 'elapsed_seconds': self.elapsed_seconds, + **({'dropped': self.dropped} if self.dropped is not None else {}) } @property @@ -1252,6 +1285,7 @@ def __init__( super().__init__(content, username, update_if_exists, None, False) self.isolated_version = isolated_version self.isolated_version_results = {} + self.dropped = None self.start_time = time.time() self.self_task_id = self_task_id self.set_task() @@ -1421,6 +1455,12 @@ def reconcile_hierarchy(self): self.hierarchy_reconciliation_done = True self.notify_progress() + def get_source_version_index(self, part_list): + if not self.isolated_version: + return None + return next((index for index, line in enumerate(part_list or []) + if (line.get('type', '') or '').lower() == 'source version'), None) + def commit_isolated_version(self, version_line): commit = IsolatedVersionCommit( version_line, UserProfile.objects.filter(username=self.username).first(), self.update_if_exists, @@ -1436,6 +1476,7 @@ def commit_isolated_version(self, version_line): else: commit.add_failed_part() result = commit.run() + self.dropped = commit.dropped # the commit owns the hierarchy, so a rejected version leaves it untouched self.hierarchy_reconciliation_done = True self.isolated_version_results.setdefault(self.get_result_key(result), []).append( @@ -1482,7 +1523,11 @@ def run(self): print("***************") while len(self.parts) > 0: part_list = self.parts.popleft() - if part_list and self.isolated_version and get(part_list, '0.type', '').lower() == 'source version': + version_index = self.get_source_version_index(part_list) + if version_index: # lines grouped before the Source Version run first, then it commits + self.parts.appendleft(part_list[version_index:]) + part_list = part_list[:version_index] + elif version_index == 0: self.commit_isolated_version(part_list[0]) part_list = part_list[1:] if part_list: @@ -1572,6 +1617,8 @@ def json_result(self): total_result['start_time'] = self.start_time_formatted total_result['elapsed_seconds'] = self.elapsed_seconds total_result['child_resource_time_distribution'] = self.resource_wise_time + if self.dropped is not None: + total_result['dropped'] = self.dropped self._json_result = total_result return self._json_result diff --git a/core/importers/tests.py b/core/importers/tests.py index 7c7fbd29b..12502dcc4 100644 --- a/core/importers/tests.py +++ b/core/importers/tests.py @@ -50,7 +50,8 @@ from core.orgs.models import Organization from core.orgs.tests.factories import OrganizationFactory from core.sources.constants import AUTO_ID_SEQUENTIAL, AUTO_ID_UUID, ISOLATED_VERSION_CONTENT_FAILED, \ - ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_NO_EDIT_ACCESS + ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_NO_EDIT_ACCESS, \ + ISOLATED_VERSION_LARGE_DROP, ISOLATED_VERSION_TARGET_MISMATCH from core.sources.models import Source from core.sources.tests.factories import OrganizationSourceFactory from core.toggles.models import Toggle @@ -6747,6 +6748,115 @@ def test_hierarchy_root_drop_rolls_back_the_hierarchy(self): self.assertEqual(self.head_concepts(), {'ROOT', 'P1', 'C'}) self.assertEqual(self.head_parents('C'), {'P1'}) + def test_rejected_version_leaves_new_and_moved_children_unlinked(self): + release = [self.concept('ROOT'), self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P1'])] + self.run_import([*release, self.version('v1')]) + self.run_import([*release, self.version('v1.1')]) # a parent's first re-import versions it once + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + head.hierarchy_root = Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')) + head.save() + + importer = self.run_import([ + self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P2']), + self.concept('N', parents=['P1']), self.version('v2')]) + + self.assertIn('hierarchy_root', importer.failed[0]['errors']) + p1 = Concept.objects.get(mnemonic='P1', id=F('versioned_object_id')) + p2 = Concept.objects.get(mnemonic='P2', id=F('versioned_object_id')) + self.assertEqual(set(p1.child_concept_queryset().values_list('mnemonic', flat=True)), {'C'}) + self.assertFalse(p2.child_concept_queryset().exists()) + self.assertEqual(self.head_parents('C'), {'P1'}) + self.assertEqual(self.head_parents('N'), set()) + + def test_content_must_be_in_the_version_source(self): + self.run_import([self.concept('A'), self.version('v1')]) + OrganizationFactory(mnemonic='Other') + + for line in (self.concept('B', source='LOINC-Staging'), self.concept('B', owner='Other'), + {**self.mapping('M', 'A', 'A'), 'owner_type': 'User'}): + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([line, self.version('v2')]) + self.assertEqual(ex.exception.messages, [ISOLATED_VERSION_TARGET_MISMATCH]) + self.assertEqual(self.head_concepts(), {'A'}) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) + + def test_ordinary_import_brings_a_dropped_concept_back(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + self.run_import([self.concept('B'), self.version('v2')]) + self.assertEqual(self.head_concepts(), {'B'}) + + importer = self.run_import([self.concept('A', names=[ + {'name': 'A renamed', 'locale': 'en', 'locale_preferred': True}])], isolated_version=False) + + self.assertEqual(len(importer.updated), 1) + self.assertEqual(self.head_concepts(), {'A', 'B'}) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + self.assertTrue(head.concepts.filter(mnemonic='A', is_latest_version=True).exists()) + + def test_version_takes_what_the_line_leaves_out_from_head(self): + self.run_import([self.concept('A'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + head.properties = [{'code': 'p1'}] + head.filters = [{'code': 'f1'}] + head.meta = {'profile': ['x']} + head.save() + + self.run_import([self.concept('A'), self.version('v2')]) + response_version = Source.objects.get(mnemonic='LOINC', version='v2') + self.assertEqual(response_version.properties, [{'code': 'p1'}]) + self.assertEqual(response_version.filters, [{'code': 'f1'}]) + self.assertEqual(response_version.meta, {'profile': ['x']}) + self.assertEqual(response_version.match_algorithms, ['es']) + + self.run_import([self.concept('A'), self.version('v3', properties=[{'code': 'p2'}])]) + head.refresh_from_db() + self.assertEqual(head.properties, [{'code': 'p2'}]) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v3').properties, [{'code': 'p2'}]) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v3').filters, [{'code': 'f1'}]) + + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=50) + def test_large_drop_needs_allow_large_drop(self): + self.run_import([self.concept('A'), self.concept('B'), self.concept('C'), self.version('v1')]) + + importer = self.run_import([self.concept('A'), self.version('v2')]) + + self.assertEqual(importer.failed[0]['errors'], {'__all__': [ISOLATED_VERSION_LARGE_DROP.format( + concepts=2, mappings=0)]}) + self.assertEqual(importer.json_result['dropped'], {'concepts': 2, 'mappings': 0}) + self.assertEqual(self.head_concepts(), {'A', 'B', 'C'}) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) + + importer = self.run_import([self.concept('A'), self.version('v2', allow_large_drop=True)]) + + self.assertEqual(len(importer.failed), 0) + self.assertEqual(importer.json_result['dropped'], {'concepts': 2, 'mappings': 0}) + self.assertEqual(self.head_concepts(), {'A'}) + self.assertNotIn('allow_large_drop', Source.objects.get(mnemonic='LOINC', version='v2').extras or {}) + + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=50) + def test_small_drop_needs_no_confirmation(self): + self.run_import([self.concept(code) for code in 'ABCDE'] + [self.version('v1')]) + + importer = self.run_import([self.concept(code) for code in 'ABC'] + [self.version('v2')]) + + self.assertEqual(len(importer.failed), 0) + self.assertEqual(self.head_concepts(), {'A', 'B', 'C'}) + + @patch('core.importers.models.post_import_update_resource_counts', Mock()) + def test_parallel_commits_the_source_version_after_lines_grouped_before_it(self): + from collections import deque + content = '\n'.join(json.dumps(line) for line in [self.source_line, self.concept('A'), self.version('v1')]) + runner = BulkImportParallelRunner(content, 'ocladmin', True, None, 'task-id', isolated_version=True) + collection_version = {'type': 'Collection Version', 'id': 'v1', 'collection': 'C', 'owner': 'Regen'} + runner.parts = deque([[collection_version, self.version('v1')]]) + calls = [] + commit = Mock(side_effect=lambda line: calls.append(('commit', line))) + with patch.object(runner, 'queue_tasks', side_effect=lambda part, _: calls.append(('queue', part))), \ + patch.object(runner, 'wait_till_tasks_alive'), patch.object(runner, 'commit_isolated_version', commit): + runner.run() + + self.assertEqual(calls, [('queue', [collection_version]), ('commit', self.version('v1'))]) + def test_commit_rolls_back_the_hierarchy_with_the_version(self): self.run_import([ self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P1']), self.version('v1')]) @@ -6931,6 +7041,9 @@ def get_ids(url): self.assertEqual( sorted(response.data['child_concept_urls']), ['/orgs/Regen/sources/LOINC/concepts/A/', '/orgs/Regen/sources/LOINC/concepts/B/']) + response = self.client.get( + '/orgs/Regen/sources/LOINC/concepts/B/', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 404) def test_version_detail_keeps_parents_dropped_from_head(self): concept = IsolatedVersionImportTest.concept @@ -6948,9 +7061,32 @@ def test_version_detail_keeps_parents_dropped_from_head(self): HTTP_AUTHORIZATION='Token ' + self.token) self.assertEqual(response.data['parent_concept_urls'], []) response = self.client.get( - '/orgs/Regen/sources/LOINC/concepts/B/', HTTP_AUTHORIZATION='Token ' + self.token) + '/orgs/Regen/sources/LOINC/concepts/P/', HTTP_AUTHORIZATION='Token ' + self.token) self.assertEqual(response.status_code, 404) + def test_nested_hierarchy_fields_follow_the_version(self): + concept = IsolatedVersionImportTest.concept + version = IsolatedVersionImportTest.version + self.run_import([concept('P'), concept('X', parents=['P']), concept('B', parents=['X']), version('v1')]) + self.run_import([concept('P'), concept('X', parents=['P']), version('v2')]) + + def get_child(repo_version): + response = self.client.get( + f'/orgs/Regen/sources/LOINC/{repo_version}/concepts/P/children/?includeChildConcepts=true', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 200) + self.assertEqual([item['id'] for item in response.data], ['X']) + return response.data[0] + + self.assertEqual(get_child('v1')['children'], ['/orgs/Regen/sources/LOINC/concepts/B/']) + self.assertTrue(get_child('v1')['has_children']) + self.assertEqual(get_child('v2')['children'], []) + self.assertFalse(get_child('v2')['has_children']) + response = self.client.get( + '/orgs/Regen/sources/LOINC/v1/concepts/B/parents/?includeParentConcepts=true', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.data[0]['parents'], ['/orgs/Regen/sources/LOINC/concepts/P/']) + @patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) @patch('core.sources.models.index_source_concepts', Mock(__name__='index_source_concepts')) diff --git a/core/settings.py b/core/settings.py index b2a403015..66ebaa48b 100644 --- a/core/settings.py +++ b/core/settings.py @@ -734,6 +734,10 @@ def get_set_from_env(name): LIST_MAX_LIMIT = int(os.environ.get('LIST_MAX_LIMIT', 100)) # Above this many new, removed or changed concepts and mappings, a changelog skips names, descriptions and prev_* CHANGELOG_ENRICHMENT_MAX_RESOURCES = int(os.environ.get('CHANGELOG_ENRICHMENT_MAX_RESOURCES', 50000)) +# An import that seeds a version is refused when it drops at least this many concepts and mappings from HEAD, and +# more than this share of them, unless its Source Version line sets allow_large_drop +SEED_FROM_IMPORT_LARGE_DROP_MIN = int(os.environ.get('SEED_FROM_IMPORT_LARGE_DROP_MIN', 1000)) +SEED_FROM_IMPORT_LARGE_DROP_PERCENT = float(os.environ.get('SEED_FROM_IMPORT_LARGE_DROP_PERCENT', 10)) ANALYTICS_API = os.environ.get('ANALYTICS_API', 'http://host.docker.internal:8002') if ANALYTICS_API: diff --git a/core/sources/constants.py b/core/sources/constants.py index 14040a458..e4716ca58 100644 --- a/core/sources/constants.py +++ b/core/sources/constants.py @@ -20,11 +20,18 @@ ISOLATED_VERSION_EXISTS = 'This Source Version already exists.' ISOLATED_VERSION_NO_EDIT_ACCESS = 'You need edit access to the source to import a version into it.' HIERARCHY_ROOT_CANNOT_BE_DROPPED = 'Hierarchy Root must be present in a version seeded from an import.' +ISOLATED_VERSION_LARGE_DROP = \ + 'Not created: this import would drop {concepts} concepts and {mappings} mappings from HEAD. Set ' \ + '"allow_large_drop": true on the Source Version line if that is intended.' +ISOLATED_VERSION_TARGET_MISMATCH = \ + 'Every concept and mapping in a seed_from_import import must be in the source of its Source Version line.' +ALLOW_LARGE_DROP = 'allow_large_drop' ISOLATED_METADATA_FIELDS = ( 'description', 'full_name', 'website', 'external_id', 'canonical_url', 'identifier', 'contact', 'jurisdiction', 'publisher', 'purpose', 'copyright', 'revision_date', 'text', 'experimental', 'source_type', 'content_type', 'supplements', 'supplement_type', 'supplement_global', 'collection_reference', 'hierarchy_meaning', 'case_sensitive', 'compositional', 'version_needed', + 'meta', 'properties', 'filters', ) ISOLATED_REQUIRED_METADATA_FIELDS = ('name', 'default_locale', 'supported_locales') HIERARCHY_MEANINGS = ( diff --git a/core/sources/models.py b/core/sources/models.py index dac059dcd..249689133 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -27,8 +27,8 @@ HIERARCHY_MEANINGS, AUTO_ID_CHOICES, AUTO_ID_SEQUENTIAL, AUTO_ID_UUID, LOCALE_EXTERNAL_AUTO_ID_CHOICES, \ SEEDED_FROM_REPO_VERSION, SEEDED_FROM_IMPORT, ISOLATED_METADATA_FIELDS, ISOLATED_REQUIRED_METADATA_FIELDS, \ HIERARCHY_ROOT_CANNOT_BE_DROPPED, ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION, DROPPED_CHILDREN_CHUNK_SIZE, \ - CONTENT_TYPE_SUPPLEMENT, SUPPLEMENTS_REQUIRED, SUPPLEMENTS_FORMAT, SEED_MEMBERS_WRITTEN, SEED_RELEASE_INDEXED, \ - SEED_STAGE + ISOLATED_VERSION_TARGET_MISMATCH, CONTENT_TYPE_SUPPLEMENT, SUPPLEMENTS_REQUIRED, SUPPLEMENTS_FORMAT, \ + SEED_MEMBERS_WRITTEN, SEED_RELEASE_INDEXED, SEED_STAGE from core.tasks.models import Task @@ -347,7 +347,22 @@ def get_import_version_line(input_list, seed_from_import): content_indexes = [index for index, _type in enumerate(types) if _type in ('concept', 'mapping')] if len(version_indexes) != 1 or (content_indexes and content_indexes[-1] > version_indexes[0]): raise ValidationError(ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION) - return input_list[version_indexes[0]] + version_line = input_list[version_indexes[0]] + Source.validate_import_targets( + version_line, {Source.get_import_target(input_list[index]) for index in content_indexes}) + return version_line + + @staticmethod + def get_import_target(line): + """The source an import line names: (owner kind, owner, source mnemonic).""" + owner_type = (line.get('owner_type', '') or '').lower() + return 'user' if owner_type in ('user', 'users') else 'org', line.get('owner'), line.get('source') + + @staticmethod + def validate_import_targets(version_line, targets): + """A seeding import's content must all be in the version's source, or the commit would empty that HEAD.""" + if any(target != Source.get_import_target(version_line) for target in targets): + raise ValidationError(ISOLATED_VERSION_TARGET_MISMATCH) def get_concept_name_locales(self): return ConceptName.objects.filter(concept__in=self.get_active_concepts()) From 5776c402653db0477440aeb3ae8eb51d3dea6057 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 19 Nov 2026 11:19:44 +0530 Subject: [PATCH 3/8] OpenConceptLab/ocl_online#655 | Source migrations renumbered after 0048_source_verification --- ...source_versioning_mode.py => 0049_source_versioning_mode.py} | 2 +- .../{0049_source_seeded_from.py => 0050_source_seeded_from.py} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename core/sources/migrations/{0048_source_versioning_mode.py => 0049_source_versioning_mode.py} (90%) rename core/sources/migrations/{0049_source_seeded_from.py => 0050_source_seeded_from.py} (97%) diff --git a/core/sources/migrations/0048_source_versioning_mode.py b/core/sources/migrations/0049_source_versioning_mode.py similarity index 90% rename from core/sources/migrations/0048_source_versioning_mode.py rename to core/sources/migrations/0049_source_versioning_mode.py index 876e163d3..3ea3e2241 100644 --- a/core/sources/migrations/0048_source_versioning_mode.py +++ b/core/sources/migrations/0049_source_versioning_mode.py @@ -6,7 +6,7 @@ class Migration(migrations.Migration): dependencies = [ - ('sources', '0047_source_supplements'), + ('sources', '0048_source_verification'), ] operations = [ diff --git a/core/sources/migrations/0049_source_seeded_from.py b/core/sources/migrations/0050_source_seeded_from.py similarity index 97% rename from core/sources/migrations/0049_source_seeded_from.py rename to core/sources/migrations/0050_source_seeded_from.py index 04008ae8d..68938e7e0 100644 --- a/core/sources/migrations/0049_source_seeded_from.py +++ b/core/sources/migrations/0050_source_seeded_from.py @@ -37,7 +37,7 @@ def backfill_seeded_from(apps, schema_editor): # pylint: disable=unused-argumen class Migration(migrations.Migration): dependencies = [ - ('sources', '0048_source_versioning_mode'), + ('sources', '0049_source_versioning_mode'), ] operations = [ From cf31316e650b88fe23527ecd96898a85464aa1fd Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 19 Nov 2026 11:42:28 +0530 Subject: [PATCH 4/8] OpenConceptLab/ocl_online#655 | Seeding imports check the drop, hierarchy root and line metadata before any content, link concepts with assigned ids and versioned parent URLs, and report archive drops --- core/concepts/models.py | 13 ++-- core/concepts/serializers.py | 15 ++-- core/importers/importer.py | 20 +++++- core/importers/models.py | 108 +++++++++++++++++++++------- core/importers/tests.py | 134 ++++++++++++++++++++++++++++------- core/sources/constants.py | 3 +- core/sources/models.py | 8 ++- 7 files changed, 237 insertions(+), 64 deletions(-) diff --git a/core/concepts/models.py b/core/concepts/models.py index 662d4340a..c138060f6 100644 --- a/core/concepts/models.py +++ b/core/concepts/models.py @@ -1478,8 +1478,8 @@ def get_import_hierarchy_map(input_list, include_parentless=False): owner = line.get('owner') source = line.get('source') if (parent_urls or include_parentless) and concept_id and owner and source: - owner_type = line.get('owner_type', '').lower() - owner_prefix = 'users' if owner_type in ['user', 'users'] else 'orgs' + owner_type = (line.get('owner_type', '') or '').lower() + owner_prefix = 'users' if owner_type == 'user' else 'orgs' # as the concept importer reads it if not is_url_encoded_string(concept_id): concept_id = encode_string(concept_id, safe='') hierarchy_map[f'/{owner_prefix}/{owner}/sources/{source}/concepts/{concept_id}/'] = parent_urls @@ -2058,8 +2058,9 @@ def __init__(self, links): def from_uri_map(cls, hierarchy_map, user=None): """hierarchy_map: child uri -> parent uris. With a user, only children it can edit and parents it can view.""" from core.sources.models import Source - resolved = Concept.get_versioned_objects_by_uri( - {*hierarchy_map, *(uri for uris in hierarchy_map.values() for uri in uris)}) + # a parent URL naming one of a concept's versions links to that concept + parent_uri_of = {uri: drop_version(uri) for uris in hierarchy_map.values() for uri in uris} + resolved = Concept.get_versioned_objects_by_uri({*hierarchy_map, *parent_uri_of.values()}) editable = viewable = None if user: sources = Source.objects.filter(id__in={source_id for _, source_id in resolved.values()}) @@ -2071,8 +2072,8 @@ def from_uri_map(cls, hierarchy_map, user=None): if not child_id or (editable is not None and child_source_id not in editable): continue links.setdefault(child_id, set()).update( - resolved[uri][0] for uri in parent_uris - if uri in resolved and (viewable is None or resolved[uri][1] in viewable)) + resolved[parent_uri_of[uri]][0] for uri in parent_uris + if parent_uri_of[uri] in resolved and (viewable is None or resolved[parent_uri_of[uri]][1] in viewable)) return cls(links) def apply(self, replace_head=False): diff --git a/core/concepts/serializers.py b/core/concepts/serializers.py index e079dfdf9..77cdbc055 100644 --- a/core/concepts/serializers.py +++ b/core/concepts/serializers.py @@ -323,16 +323,23 @@ def get_mappings(self, obj): # pylint: disable=too-many-locals def get_child_concepts(self, obj): if self.include_child_concepts: - return ConceptDetailSerializer( - get_viewable_concepts(obj.child_concepts.all(), get(self, 'context.request')), many=True).data + return ConceptDetailSerializer(get_viewable_concepts( + self.get_related_concepts(obj, 'child_concepts'), get(self, 'context.request')), many=True).data return None def get_parent_concepts(self, obj): if self.include_parent_concepts: - return ConceptDetailSerializer( - get_viewable_concepts(obj.parent_concepts.all(), get(self, 'context.request')), many=True).data + return ConceptDetailSerializer(get_viewable_concepts( + self.get_related_concepts(obj, 'parent_concepts'), get(self, 'context.request')), many=True).data return None + def get_related_concepts(self, obj, relation): + """The concept's own links, or with a source version in the context, those in that version.""" + repo_version = get(self, 'context.repo_version') + if repo_version: + return obj.get_version_hierarchy_queryset(relation, repo_version) + return getattr(obj, relation).all() + def get_hierarchy_path(self, obj): if self.include_hierarchy_path: return obj.get_hierarchy_path(get(self, 'context.request.user')) diff --git a/core/importers/importer.py b/core/importers/importer.py index b7e328dff..fd6547639 100644 --- a/core/importers/importer.py +++ b/core/importers/importer.py @@ -80,6 +80,7 @@ class ImportTaskSummary(BaseModel): unchanged: int = 0 failures: list = [] dependencies: list = [] + dropped: dict = None class ImportTask(BaseModel): @@ -160,6 +161,7 @@ def summary(self) -> ImportTaskSummary: # pylint: disable=too-many-branches for result in results: if isinstance(result, dict): + summary.dropped = result.get('dropped', summary.dropped) continue summary.processed += 1 if result == CREATED: @@ -238,6 +240,7 @@ def __init__( # pylint: disable=too-many-arguments self.isolated_version = isolated_version self.version_lines = [] self.content_targets = set() + self.content_lines = [] # what preflight needs of each Concept and Mapping line in a seeding import def validate_versioning(self, resources, resource_types): if not self.isolated_version: @@ -247,7 +250,8 @@ def validate_versioning(self, resources, resource_types): raise ValidationError(ISOLATED_VERSION_NEEDS_ONE_SOURCE_VERSION) Source.validate_import_targets(self.version_lines[0], self.content_targets) IsolatedVersionCommit( - self.version_lines[0], UserProfile.objects.filter(username=self.username).first(), True).preflight() + self.version_lines[0], UserProfile.objects.filter(username=self.username).first(), True).preflight( + self.content_lines) except DjangoValidationError as ex: raise ValidationError(ex.message_dict if hasattr(ex, 'error_dict') else ex.messages) from ex return self.get_isolated_version_resource_types(resource_types) @@ -541,6 +545,7 @@ def collect_version_line(self, line, prefix, event, value): self.version_lines.append(line) elif event == 'end_map' and get(line, 'type') in ('Concept', 'Mapping') and self.isolated_version: self.content_targets.add(Source.get_import_target(line)) + self.content_lines.append({'type': line['type'], 'id': line.get('id')}) return line if event == 'map_key' else None if line is not None and '.' not in prefix: if event in ('string', 'number', 'boolean', 'null'): @@ -734,7 +739,9 @@ def __init__( self.isolated_version = isolated_version self.previous_subtask_ids = previous_subtask_ids or [] self.import_task_id = import_task_id + self.dropped = None self.seen = {'concepts': set(), 'mappings': set()} + self.assigned_hierarchy = {} self.hierarchy_map = {} def run(self): # pylint: disable=too-many-branches @@ -779,7 +786,8 @@ def run(self): # pylint: disable=too-many-branches self.indexer.finish() if self.isolated and not self.isolated_version: - results.append({'seen': {key: sorted(value) for key, value in self.seen.items()}}) + results.append({'seen': { + **{key: sorted(value) for key, value in self.seen.items()}, 'hierarchy': self.assigned_hierarchy}}) return results def collect_hierarchy_map(self, temp, is_zipped, is_tarred): @@ -811,7 +819,9 @@ def commit_isolated_version(self, version_line): import_task_id=self.import_task_id) for results in self.iter_previous_results(): commit.add_subtask_results(results) - return commit.run() + result = commit.run() + self.dropped = commit.dropped + return result def iter_previous_results(self): """Each earlier subtask's results in turn, so only one is held at a time.""" @@ -877,6 +887,8 @@ def add_seen(self, importer, result): versioned_object_id = importer.get_seen_versioned_object_id(result) if importer else None if versioned_object_id: self.seen['concepts' if isinstance(importer, ConceptImporter) else 'mappings'].add(versioned_object_id) + if isinstance(importer, ConceptImporter): + self.assigned_hierarchy.update(importer.get_assigned_hierarchy(result)) @staticmethod def add_exception_to_results(file, start_index, end_index, count, ex, results): @@ -919,6 +931,8 @@ def import_resource(self, json_file, filepath, start_index, end_index): # pylin if isinstance(result, int): results.append(result) self.add_seen(get(resource_importer, 'importer'), result) + if self.dropped is not None: + results.append({'dropped': self.dropped}) else: results.append(f'{error} due to: {result}') except Exception as e: diff --git a/core/importers/models.py b/core/importers/models.py index e6c740104..f1f2d5352 100644 --- a/core/importers/models.py +++ b/core/importers/models.py @@ -24,7 +24,7 @@ from core.orgs.models import Organization from core.sources.constants import ISOLATED_METADATA_FIELDS, ISOLATED_VERSION_CONTENT_FAILED, \ ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_NO_EDIT_ACCESS, SEEDED_FROM_IMPORT, \ - ISOLATED_VERSION_LARGE_DROP, ALLOW_LARGE_DROP + ISOLATED_VERSION_LARGE_DROP, ALLOW_LARGE_DROP, ISOLATED_VERSION_META_INVALID, HIERARCHY_ROOT_CANNOT_BE_DROPPED from core.sources.models import Source from core.tasks.models import Task from core.users.models import UserProfile @@ -327,7 +327,7 @@ def delete(self): class SourceVersionImporter(BaseResourceImporter): mandatory_fields = {"id"} allowed_fields = [ - "id", "released", "name", "default_locale", "supported_locales", "extras", "match_algorithms", + "id", "released", "name", "default_locale", "supported_locales", "extras", *ISOLATED_METADATA_FIELDS ] @@ -364,6 +364,10 @@ def __init__( # pylint: disable=too-many-arguments def process(self): source = Source(**self.data) self.set_head_defaults(source) + try: + self.validate_metadata(self.data) + except ValidationError as ex: + return ex.message_dict if self.isolated_version: source.seeded_from = {'type': SEEDED_FROM_IMPORT, 'task': self.import_task_id} source._metadata_fields = list(self.data.keys()) # pylint: disable=protected-access @@ -373,6 +377,20 @@ def process(self): return PERMISSION_DENIED + @staticmethod + def validate_metadata(line): + """ + The checks a source's save runs, on the metadata a version line sets; persisting a version skips them. Values + a version takes from HEAD aren't checked again. + """ + probe = Source(**{field: line[field] for field in ISOLATED_METADATA_FIELDS if field in line}) + probe.clean_properties() + probe.clean_filters() + if 'match_algorithms' in line: + probe.clean_match_algorithms() + if probe.meta is not None and not isinstance(probe.meta, dict): + raise ValidationError({'meta': [ISOLATED_VERSION_META_INVALID]}) + def set_head_defaults(self, source): """What the line leaves out comes from HEAD, as for POST .../versions/.""" head = source.head @@ -415,6 +433,7 @@ def __init__( # pylint: disable=too-many-arguments def add_seen(self, seen): self.seen_concept_ids.update(get(seen, 'concepts') or []) self.seen_mapping_ids.update(get(seen, 'mappings') or []) + self.hierarchy_map.update(get(seen, 'hierarchy') or {}) def add_runner_result(self, result): """Folds in one BulkImportInline part's result, so the parts are read once and not kept.""" @@ -433,11 +452,9 @@ def add_subtask_results(self, results): self.content_failures += 1 def get_head(self): - owner_type = (self.version_line.get('owner_type', '') or '').lower() - owner_filter = 'user__username' if owner_type in ['user', 'users'] else 'organization__mnemonic' - return Source.objects.filter( - **{owner_filter: self.version_line.get('owner')}, mnemonic=self.version_line.get('source'), - version=HEAD).first() + owner_kind, owner, source = Source.get_import_target(self.version_line) + owner_filter = 'user__username' if owner_kind == 'user' else 'organization__mnemonic' + return Source.objects.filter(**{owner_filter: owner}, mnemonic=source, version=HEAD).first() def get_rejection(self, importer, needs_head=True): """(True, result) when this version would be rejected. A HEAD the import itself creates isn't there yet.""" @@ -449,14 +466,53 @@ def get_rejection(self, importer, needs_head=True): return True, PERMISSION_DENIED return False, None - def preflight(self): - """Runs before any content imports, so a version that would be rejected leaves HEAD untouched.""" + def preflight(self, content_lines=()): + """ + Runs before any content imports, so a version that would be rejected leaves HEAD untouched. content_lines are + the import's Concept and Mapping lines, for what HEAD would lose. + """ importer = SourceVersionImporter({**self.version_line}, self.user, self.update_if_exists, isolated_version=True) rejected, result = self.get_rejection(importer, needs_head=False) if rejected: raise ValidationError(result if isinstance(result, dict) else {'__all__': [{ False: ISOLATED_VERSION_LINE_INVALID, None: ISOLATED_VERSION_EXISTS, PERMISSION_DENIED: ISOLATED_VERSION_NO_EDIT_ACCESS}[result]]}) + SourceVersionImporter.validate_metadata(self.version_line) + head = self.get_head() + if head: + self.check_planned_drop(head, content_lines) + + def check_planned_drop(self, head, content_lines): + """ + Refuses, before any content imports, a file that leaves out HEAD's hierarchy root, or that leaves out at least + SEED_FROM_IMPORT_LARGE_DROP_MIN of HEAD's codes and more than its percent of them, unless allow_large_drop. + Mapping lines without an id are matched at import, so each is counted as keeping one of HEAD's mappings. + """ + concept_ids, mapping_ids, unnamed_mappings = set(), set(), 0 + for line in content_lines: + line_id = line.get('id') + if (line.get('type', '') or '').lower() == 'concept': + if line_id: + concept_ids.add(line_id if is_url_encoded_string(line_id) else encode_string(line_id, safe='')) + elif line_id: + mapping_ids.add(line_id) + else: + unnamed_mappings += 1 + head_concepts = set(head.concepts_set.filter( + id=F('versioned_object_id'), is_active=True).values_list('mnemonic', flat=True)) + head_mappings = set(head.mappings_set.filter( + id=F('versioned_object_id'), is_active=True).values_list('mnemonic', flat=True)) + root_mnemonic = get(head, 'hierarchy_root.mnemonic') + if root_mnemonic and root_mnemonic in head_concepts and root_mnemonic not in concept_ids: + raise ValidationError({'hierarchy_root': [HIERARCHY_ROOT_CANNOT_BE_DROPPED]}) + dropped = { + 'concepts': len(head_concepts - concept_ids), + 'mappings': max(len(head_mappings - mapping_ids) - unnamed_mappings, 0) + } + total = dropped['concepts'] + dropped['mappings'] + if not self.allow_large_drop and total >= settings.SEED_FROM_IMPORT_LARGE_DROP_MIN and \ + total * 100 > settings.SEED_FROM_IMPORT_LARGE_DROP_PERCENT * (len(head_concepts) + len(head_mappings)): + raise ValidationError({'__all__': [ISOLATED_VERSION_LARGE_DROP.format(**dropped)]}) def run(self): if self.content_failures: @@ -472,8 +528,6 @@ def run(self): with transaction.atomic(): Concept.reconcile_import_hierarchy(self.hierarchy_map, self.user, replace_head=True) self.dropped = head.drop_unseen_children(self.seen_concept_ids, self.seen_mapping_ids) - if self.is_large_drop(): - raise IsolatedVersionRollback({'__all__': [ISOLATED_VERSION_LARGE_DROP.format(**self.dropped)]}) result = importer.process() if result != CREATED: raise IsolatedVersionRollback(result) @@ -483,15 +537,6 @@ def run(self): return get(ex, 'message_dict') or {'__all__': ex.messages} return CREATED - def is_large_drop(self): - """At least SEED_FROM_IMPORT_LARGE_DROP_MIN of HEAD's codes leave it, and more than its percent of them.""" - if self.allow_large_drop: - return False - dropped = self.dropped['concepts'] + self.dropped['mappings'] - kept = len(self.seen_concept_ids) + len(self.seen_mapping_ids) - return dropped >= settings.SEED_FROM_IMPORT_LARGE_DROP_MIN and \ - dropped * 100 > settings.SEED_FROM_IMPORT_LARGE_DROP_PERCENT * (dropped + kept) - class CollectionImporter(BaseResourceImporter): mandatory_fields = {'id', 'name', 'owner_type', 'owner'} @@ -601,6 +646,14 @@ def __init__( # pylint: disable=too-many-arguments self.skip_hierarchy_tasks = skip_hierarchy_tasks self.version = False self.instance = None + self.assigns_id = not get(data, 'id') + self.line_parent_urls = get(data, 'parent_concept_urls') or [] + + def get_assigned_hierarchy(self, result): + """A new concept's parents when the import assigned its id, so the version commit can link it.""" + if self.isolated and self.assigns_id and result == CREATED and get(self, 'instance.uri'): + return {drop_version(self.instance.uri): self.line_parent_urls} + return {} def exists(self): return self.get_queryset().exists() @@ -1031,6 +1084,7 @@ def __init__( # pylint: disable=too-many-arguments self.isolated = isolated or isolated_version self.seen_concept_ids = set() self.seen_mapping_ids = set() + self.assigned_hierarchy = {} # Lookup cache shared across this run's items (see ConceptImporter/MappingImporter). # It caches misses too (None/False), so it's only safe because a chunk is single-resource-type # in the production parallel path (BulkImportParallelRunner.make_parts splits concepts and @@ -1066,7 +1120,8 @@ def __init__( # pylint: disable=too-many-arguments def preflight_isolated_version(self, version_line): if version_line: - IsolatedVersionCommit(version_line, self.user, self.update_if_exists).preflight() + IsolatedVersionCommit(version_line, self.user, self.update_if_exists).preflight( + Source.get_import_content_lines(self.input_list)) def set_task(self): self.task = Task.objects.filter(id=self.self_task_id).first() @@ -1082,7 +1137,8 @@ def import_source_version(self, item): return SourceVersionImporter(item, self.user, self.update_if_exists).run() commit = IsolatedVersionCommit( item, self.user, self.update_if_exists, - hierarchy_map=Concept.get_import_hierarchy_map(self.input_list, include_parentless=True), + hierarchy_map={**Concept.get_import_hierarchy_map(self.input_list, include_parentless=True), + **self.assigned_hierarchy}, seen_concept_ids=self.seen_concept_ids, seen_mapping_ids=self.seen_mapping_ids, content_failures=self.content_failures_count, import_task_id=self.self_task_id ) @@ -1199,6 +1255,7 @@ def run(self): # pylint: disable=too-many-branches,too-many-statements,too-many _result = concept_importer.delete() if action == 'delete' else concept_importer.run() indexer.add(concept_importer.instance) self.seen_concept_ids.update(compact([concept_importer.get_seen_versioned_object_id(_result)])) + self.assigned_hierarchy.update(concept_importer.get_assigned_hierarchy(_result)) except Exception as ex: ERRBIT_LOGGER.log(ex) _result = {'__all__': str(ex)} @@ -1274,7 +1331,9 @@ def make_result(self): 'report': self.report } if self.isolated and not self.isolated_version: - self.result['seen'] = {'concepts': sorted(self.seen_concept_ids), 'mappings': sorted(self.seen_mapping_ids)} + self.result['seen'] = { + 'concepts': sorted(self.seen_concept_ids), 'mappings': sorted(self.seen_mapping_ids), + 'hierarchy': self.assigned_hierarchy} class BulkImportParallelRunner(BaseImporter): # pragma: no cover @@ -1309,7 +1368,8 @@ def __init__( self.index = should_index_import(index, self.total) version_line = Source.get_import_version_line(self.input_list, self.isolated_version) if version_line: - IsolatedVersionCommit(version_line, self.user, self.update_if_exists).preflight() + IsolatedVersionCommit(version_line, self.user, self.update_if_exists).preflight( + Source.get_import_content_lines(self.input_list)) self.make_resource_distribution() self.make_parts() self.collect_concept_hierarchy_map() diff --git a/core/importers/tests.py b/core/importers/tests.py index 12502dcc4..67b5c18f4 100644 --- a/core/importers/tests.py +++ b/core/importers/tests.py @@ -6564,10 +6564,10 @@ def test_isolated_import_fails_when_hierarchy_root_is_dropped(self): head.hierarchy_root = Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')) head.save() - importer = self.run_import([self.concept('A'), self.version('v2')]) + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept('A'), self.version('v2')]) - self.assertEqual(len(importer.failed), 1) - self.assertIn('hierarchy_root', importer.failed[0]['errors']) + self.assertIn('hierarchy_root', ex.exception.message_dict) self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) self.assertTrue(Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')).is_active) @@ -6742,25 +6742,26 @@ def test_hierarchy_root_drop_rolls_back_the_hierarchy(self): head.hierarchy_root = Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')) head.save() - importer = self.run_import([self.concept('P1'), self.concept('C'), self.version('v2')]) + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept('P1'), self.concept('C'), self.version('v2')]) - self.assertIn('hierarchy_root', importer.failed[0]['errors']) + self.assertIn('hierarchy_root', ex.exception.message_dict) self.assertEqual(self.head_concepts(), {'ROOT', 'P1', 'C'}) self.assertEqual(self.head_parents('C'), {'P1'}) def test_rejected_version_leaves_new_and_moved_children_unlinked(self): - release = [self.concept('ROOT'), self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P1'])] + release = [self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P1'])] self.run_import([*release, self.version('v1')]) self.run_import([*release, self.version('v1.1')]) # a parent's first re-import versions it once - head = Source.objects.get(mnemonic='LOINC', version='HEAD') - head.hierarchy_root = Concept.objects.get(mnemonic='ROOT', id=F('versioned_object_id')) - head.save() + failing_line = self.concept('BAD') + failing_line.pop('concept_class') importer = self.run_import([ self.concept('P1'), self.concept('P2'), self.concept('C', parents=['P2']), - self.concept('N', parents=['P1']), self.version('v2')]) + self.concept('N', parents=['P1']), failing_line, self.version('v2')]) - self.assertIn('hierarchy_root', importer.failed[0]['errors']) + self.assertEqual(importer.failed[-1]['errors'], {'__all__': [ISOLATED_VERSION_CONTENT_FAILED]}) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) p1 = Concept.objects.get(mnemonic='P1', id=F('versioned_object_id')) p2 = Concept.objects.get(mnemonic='P2', id=F('versioned_object_id')) self.assertEqual(set(p1.child_concept_queryset().values_list('mnemonic', flat=True)), {'C'}) @@ -6796,33 +6797,34 @@ def test_ordinary_import_brings_a_dropped_concept_back(self): def test_version_takes_what_the_line_leaves_out_from_head(self): self.run_import([self.concept('A'), self.version('v1')]) head = Source.objects.get(mnemonic='LOINC', version='HEAD') - head.properties = [{'code': 'p1'}] - head.filters = [{'code': 'f1'}] + head.properties = [{'code': 'p1', 'type': 'string'}] + head.filters = [{'code': 'f1', 'operator': ['='], 'value': 'x'}] head.meta = {'profile': ['x']} head.save() self.run_import([self.concept('A'), self.version('v2')]) response_version = Source.objects.get(mnemonic='LOINC', version='v2') - self.assertEqual(response_version.properties, [{'code': 'p1'}]) - self.assertEqual(response_version.filters, [{'code': 'f1'}]) + self.assertEqual(response_version.properties, [{'code': 'p1', 'type': 'string'}]) + self.assertEqual(response_version.filters, [{'code': 'f1', 'operator': ['='], 'value': 'x'}]) self.assertEqual(response_version.meta, {'profile': ['x']}) self.assertEqual(response_version.match_algorithms, ['es']) - self.run_import([self.concept('A'), self.version('v3', properties=[{'code': 'p2'}])]) + self.run_import([self.concept('A'), self.version('v3', properties=[{'code': 'p2', 'type': 'string'}])]) head.refresh_from_db() - self.assertEqual(head.properties, [{'code': 'p2'}]) - self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v3').properties, [{'code': 'p2'}]) - self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v3').filters, [{'code': 'f1'}]) + self.assertEqual(head.properties, [{'code': 'p2', 'type': 'string'}]) + version = Source.objects.get(mnemonic='LOINC', version='v3') + self.assertEqual(version.properties, [{'code': 'p2', 'type': 'string'}]) + self.assertEqual(version.filters, [{'code': 'f1', 'operator': ['='], 'value': 'x'}]) @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=50) def test_large_drop_needs_allow_large_drop(self): self.run_import([self.concept('A'), self.concept('B'), self.concept('C'), self.version('v1')]) - importer = self.run_import([self.concept('A'), self.version('v2')]) + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept('A'), self.version('v2')]) - self.assertEqual(importer.failed[0]['errors'], {'__all__': [ISOLATED_VERSION_LARGE_DROP.format( + self.assertEqual(ex.exception.message_dict, {'__all__': [ISOLATED_VERSION_LARGE_DROP.format( concepts=2, mappings=0)]}) - self.assertEqual(importer.json_result['dropped'], {'concepts': 2, 'mappings': 0}) self.assertEqual(self.head_concepts(), {'A', 'B', 'C'}) self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) @@ -6833,6 +6835,85 @@ def test_large_drop_needs_allow_large_drop(self): self.assertEqual(self.head_concepts(), {'A'}) self.assertNotIn('allow_large_drop', Source.objects.get(mnemonic='LOINC', version='v2').extras or {}) + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=50) + def test_refused_drop_leaves_head_content_unchanged(self): + self.run_import([self.concept('P'), self.concept('C', parents=['P']), self.concept('D'), self.concept('E'), + self.version('v1')]) + + with self.assertRaises(DjangoValidationError): + self.run_import([self.concept('P', names=[{'name': 'P renamed', 'locale': 'en', 'locale_preferred': True}]), + self.concept('N', parents=['P']), self.version('v2')]) + + self.assertEqual(self.head_concepts(), {'P', 'C', 'D', 'E'}) + self.assertEqual(Concept.objects.get(mnemonic='P', id=F('versioned_object_id')).display_name, 'P name') + self.assertFalse(Concept.objects.filter(mnemonic='N').exists()) + self.assertEqual(self.head_parents('C'), {'P'}) + + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=50) + def test_new_codes_do_not_dilute_the_drop(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept(f'N{index}') for index in range(5)] + [self.version('v2')]) + + self.assertEqual(ex.exception.message_dict, {'__all__': [ISOLATED_VERSION_LARGE_DROP.format( + concepts=2, mappings=0)]}) + self.assertEqual(self.head_concepts(), {'A', 'B'}) + + def test_concept_with_an_assigned_id_keeps_its_parents(self): + self.run_import([self.concept('P'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + head.autoid_concept_mnemonic = AUTO_ID_SEQUENTIAL + head.save() # creates the sequence + line = self.concept('ignored', parents=['P']) + line.pop('id') + + importer = self.run_import([self.concept('P'), line, self.version('v2')]) + + self.assertEqual(len(importer.failed), 0) + new = Concept.objects.get(id=F('versioned_object_id'), parent__mnemonic='LOINC', mnemonic__regex=r'^[0-9]+$') + self.assertEqual(self.head_parents(new.mnemonic), {'P'}) + self.assertEqual(self.members('v2'), {'P', new.mnemonic}) + self.assertEqual(set(new.get_version_hierarchy_queryset( + 'parent_concepts', Source.objects.get(mnemonic='LOINC', version='v2')).values_list('mnemonic', flat=True)), + {'P'}) + + def test_parent_url_naming_a_concept_version_links_the_concept(self): + self.run_import([self.concept('P'), self.version('v1')]) + version_uri = Concept.objects.get(mnemonic='P', is_latest_version=True).uri + + self.run_import([self.concept('P'), {**self.concept('C'), 'parent_concept_urls': [version_uri]}, + self.version('v2')]) + + self.assertEqual(self.head_parents('C'), {'P'}) + + def test_version_line_metadata_is_validated_before_content(self): + self.run_import([self.concept('A'), self.version('v1')]) + + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept('A'), self.concept('B'), self.version('v2', filters=['status'])]) + + self.assertIn('filters', ex.exception.message_dict) + self.assertEqual(self.head_concepts(), {'A'}) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='HEAD').filters, []) + importer = self.run_import([self.version('v2', filters=['status'])], isolated_version=False) + self.assertIn('filters', importer.failed[0]['errors']) + self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) + + def test_seeding_line_match_algorithms_reach_head(self): + self.run_import([self.concept('A'), self.version('v1')]) + Source.objects.filter(mnemonic='LOINC', version='HEAD').update(match_algorithms=['es', 'llm']) + + self.run_import([self.concept('A'), self.version('v2', match_algorithms=['es'])]) + + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='HEAD').match_algorithms, ['es']) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v2').match_algorithms, ['es']) + + def test_plural_user_owner_type_is_read_as_the_importers_read_it(self): + users_line = {'owner_type': 'users', 'owner': 'Regen', 'source': 'LOINC'} + self.assertEqual(Source.get_import_target(users_line), ('org', 'Regen', 'LOINC')) + self.assertEqual(Source.get_import_target({**users_line, 'owner_type': 'User'}), ('user', 'Regen', 'LOINC')) + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=50) def test_small_drop_needs_no_confirmation(self): self.run_import([self.concept(code) for code in 'ABCDE'] + [self.version('v1')]) @@ -7080,8 +7161,10 @@ def get_child(repo_version): self.assertEqual(get_child('v1')['children'], ['/orgs/Regen/sources/LOINC/concepts/B/']) self.assertTrue(get_child('v1')['has_children']) + self.assertEqual([item['id'] for item in get_child('v1')['child_concepts']], ['B']) self.assertEqual(get_child('v2')['children'], []) self.assertFalse(get_child('v2')['has_children']) + self.assertEqual(get_child('v2')['child_concepts'], []) response = self.client.get( '/orgs/Regen/sources/LOINC/v1/concepts/B/parents/?includeParentConcepts=true', HTTP_AUTHORIZATION='Token ' + self.token) @@ -7124,8 +7207,11 @@ def import_zip(self, concepts, mappings, version): import_task_id='zip-task-id').run() def test_isolated_version_zip_import(self): - self.assertEqual(self.import_zip([('A',), ('B',)], [('M1', 'A', 'B')], 'v1'), [CREATED]) - self.assertEqual(self.import_zip([('B',), ('C', ['B'])], [], 'v2'), [CREATED]) + self.assertEqual( + self.import_zip([('A',), ('B',)], [('M1', 'A', 'B')], 'v1'), + [CREATED, {'dropped': {'concepts': 0, 'mappings': 0}}]) + self.assertEqual( + self.import_zip([('B',), ('C', ['B'])], [], 'v2'), [CREATED, {'dropped': {'concepts': 1, 'mappings': 1}}]) self.assertEqual(IsolatedVersionImportTest.members('v1'), {'A', 'B'}) self.assertEqual(IsolatedVersionImportTest.members('v2'), {'B', 'C'}) diff --git a/core/sources/constants.py b/core/sources/constants.py index e4716ca58..6b8a06d47 100644 --- a/core/sources/constants.py +++ b/core/sources/constants.py @@ -26,12 +26,13 @@ ISOLATED_VERSION_TARGET_MISMATCH = \ 'Every concept and mapping in a seed_from_import import must be in the source of its Source Version line.' ALLOW_LARGE_DROP = 'allow_large_drop' +ISOLATED_VERSION_META_INVALID = 'meta must be an object.' ISOLATED_METADATA_FIELDS = ( 'description', 'full_name', 'website', 'external_id', 'canonical_url', 'identifier', 'contact', 'jurisdiction', 'publisher', 'purpose', 'copyright', 'revision_date', 'text', 'experimental', 'source_type', 'content_type', 'supplements', 'supplement_type', 'supplement_global', 'collection_reference', 'hierarchy_meaning', 'case_sensitive', 'compositional', 'version_needed', - 'meta', 'properties', 'filters', + 'meta', 'properties', 'filters', 'match_algorithms', ) ISOLATED_REQUIRED_METADATA_FIELDS = ('name', 'default_locale', 'supported_locales') HIERARCHY_MEANINGS = ( diff --git a/core/sources/models.py b/core/sources/models.py index 249689133..0fd0f8431 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -352,11 +352,15 @@ def get_import_version_line(input_list, seed_from_import): version_line, {Source.get_import_target(input_list[index]) for index in content_indexes}) return version_line + @staticmethod + def get_import_content_lines(input_list): + return [line for line in input_list if (line.get('type', '') or '').lower() in ('concept', 'mapping')] + @staticmethod def get_import_target(line): - """The source an import line names: (owner kind, owner, source mnemonic).""" + """The source an import line names: (owner kind, owner, source mnemonic), read as the importers read it.""" owner_type = (line.get('owner_type', '') or '').lower() - return 'user' if owner_type in ('user', 'users') else 'org', line.get('owner'), line.get('source') + return 'user' if owner_type == 'user' else 'org', line.get('owner'), line.get('source') @staticmethod def validate_import_targets(version_line, targets): From 820cb326f105110e4af9550c0e4afecaf42e3ff0 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 19 Nov 2026 12:35:09 +0530 Subject: [PATCH 5/8] OpenConceptLab/ocl_online#655 | Seeding preflight matches idless mappings, refuses delete lines and reads archive lines whole; dropped codes leave HEAD's comparisons and concept mappings; archive summaries round-trip --- core/common/tasks.py | 12 +++- core/concepts/models.py | 37 +++++++++- core/concepts/serializers.py | 4 +- core/concepts/views.py | 7 +- core/importers/importer.py | 40 +++++------ core/importers/models.py | 112 ++++++++++++++++++++++++++----- core/importers/tests.py | 126 ++++++++++++++++++++++++++++++++++- core/sources/constants.py | 4 +- core/sources/models.py | 19 ++++-- 9 files changed, 308 insertions(+), 53 deletions(-) diff --git a/core/common/tasks.py b/core/common/tasks.py index 503036e49..59c6b3c25 100644 --- a/core/common/tasks.py +++ b/core/common/tasks.py @@ -705,13 +705,19 @@ def index_expansion_mappings(expansion_id, count=None, mapping_ids=None): # pyl @app.task def make_hierarchy(concept_map): - """concept_map: parent uri -> child uris. Adds the links, never removes any.""" + """ + concept_map: parent uri -> child uris. Adds the links, never removes any. A child URL naming a concept version + links that version and its concept's latest version. + """ + from core.common.utils import drop_version from core.concepts.models import ImportHierarchy - child_map = {} + child_map, version_child_map = {}, {} for parent_uri, child_uris in concept_map.items(): for child_uri in child_uris: - child_map.setdefault(child_uri, []).append(parent_uri) + target = version_child_map if drop_version(child_uri) != child_uri else child_map + target.setdefault(child_uri, []).append(parent_uri) ImportHierarchy.from_uri_map(child_map).apply() + ImportHierarchy.link_child_versions(version_child_map) @app.task(ignore_result=True, base=QueueOnceCustomTask) diff --git a/core/concepts/models.py b/core/concepts/models.py index c138060f6..1ef02f113 100644 --- a/core/concepts/models.py +++ b/core/concepts/models.py @@ -1323,7 +1323,14 @@ def __get_mappings_from_relation(self, relation_manager, is_latest=False): if is_latest: return mappings.filter(is_latest_version=True) - return mappings.filter(id=F('versioned_object_id')) + return mappings.filter(id=F('versioned_object_id'), is_active=True) # not those dropped from HEAD + + def get_version_mappings(self, repo_version, include_indirect=False): + """The mappings of repo_version from this concept, and with include_indirect those to it.""" + criteria = Q(from_concept__versioned_object_id=self.versioned_object_id) + if include_indirect: + criteria |= Q(to_concept__versioned_object_id=self.versioned_object_id) + return repo_version.mappings.filter(criteria) def get_bidirectional_mappings(self): return self.get_unidirectional_mappings() | self.get_indirect_mappings() @@ -2076,6 +2083,34 @@ def from_uri_map(cls, hierarchy_map, user=None): if parent_uri_of[uri] in resolved and (viewable is None or resolved[parent_uri_of[uri]][1] in viewable)) return cls(links) + @classmethod + def link_child_versions(cls, version_child_map): + """version_child_map: child version uri -> parent uris. Links each named row and its latest version.""" + if not version_child_map: + return + rows = {} + for batch in chunks(sorted(version_child_map), cls.CHUNK_SIZE): + for row_id, versioned_object_id, uri in Concept.objects.filter(uri__in=batch).values_list( + 'id', 'versioned_object_id', 'uri'): + rows[uri] = (row_id, versioned_object_id) + parent_uris = {drop_version(uri) for uris in version_child_map.values() for uri in uris} + parents = { + uri: concept_id for uri, (concept_id, _) in Concept.get_versioned_objects_by_uri(parent_uris).items()} + latest = Concept.get_latest_version_ids_by_versioned_object_id( + {*parents.values(), *(versioned_object_id for _, versioned_object_id in rows.values())}) + pairs = set() + for child_uri, uris in version_child_map.items(): + if child_uri not in rows: + continue + row_id, versioned_object_id = rows[child_uri] + for parent_uri in uris: + parent_id = latest.get(parents.get(drop_version(parent_uri))) + if parent_id: + pairs.add((row_id, parent_id)) + if versioned_object_id in latest: + pairs.add((latest[versioned_object_id], parent_id)) + cls.add_links(pairs) + def apply(self, replace_head=False): for batch in chunks(sorted(self.links), self.CHUNK_SIZE): parents = { diff --git a/core/concepts/serializers.py b/core/concepts/serializers.py index 77cdbc055..8679e39ee 100644 --- a/core/concepts/serializers.py +++ b/core/concepts/serializers.py @@ -36,7 +36,7 @@ def get_viewable_concepts(queryset, request): class ViewableHierarchyUrlsField(ListField): """ A concept's parent or child concept URLs (`relation`), of concepts in repos the requester can view: the context's - `user`, else its request's user. + `user`, else its request's user. With a `repo_version` in the context, those in that version. """ def __init__(self, relation, **kwargs): self.relation = relation @@ -44,7 +44,7 @@ def __init__(self, relation, **kwargs): def get_attribute(self, instance): user = self.context['user'] if 'user' in self.context else get(self.context, 'request.user') - return instance.get_viewable_hierarchy_concept_urls(self.relation, user) + return instance.get_viewable_hierarchy_concept_urls(self.relation, user, self.context.get('repo_version')) class LocalizedNameSerializer(ModelSerializer): diff --git a/core/concepts/views.py b/core/concepts/views.py index 42b1ac61e..bcdcfc14d 100644 --- a/core/concepts/views.py +++ b/core/concepts/views.py @@ -725,7 +725,7 @@ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) -class ConceptMappingsView(ConceptBaseView, ListWithHeadersMixin): +class ConceptMappingsView(ConceptHierarchyMixin, ConceptBaseView, ListWithHeadersMixin): is_page_size_capped = True serializer_class = MappingListSerializer permission_classes = (CanViewParentDictionary,) @@ -741,7 +741,10 @@ def get_queryset(self): is_collection = 'collection' in self.kwargs collection_version = self.kwargs.get('version', HEAD) if is_collection else None parent_uri = get_collection_uri_from_view(self, self.request) if is_collection else None - if include_indirect_mappings: + repo_version = None if is_collection else self.get_source_version() + if repo_version: + mappings_queryset = concept.get_version_mappings(repo_version, include_indirect_mappings) + elif include_indirect_mappings: mappings_queryset = concept.get_bidirectional_mappings_for_collection( parent_uri, collection_version ) if is_collection else concept.get_bidirectional_mappings() diff --git a/core/importers/importer.py b/core/importers/importer.py index fd6547639..104fd3943 100644 --- a/core/importers/importer.py +++ b/core/importers/importer.py @@ -80,7 +80,7 @@ class ImportTaskSummary(BaseModel): unchanged: int = 0 failures: list = [] dependencies: list = [] - dropped: dict = None + dropped: dict | None = None class ImportTask(BaseModel): @@ -517,9 +517,9 @@ def categorize_resources(self, json_file, path, file_path, resource_types, resou try: parser = ijson.parse(json_file, multiple_values=True, allow_comments=True) - line = None # top-level scalar fields of the current resource, to keep its Source Version lines + builder = None # the current resource, built whole only for a seeding import for prefix, event, value in parser: - line = self.collect_version_line(line, prefix, event, value) + builder = self.collect_seeding_line(builder, prefix, event, value) # Expect {"resourceType": ""}{"resourceType": ""} or {"type": ""}{"type": ""} if event == 'string' and (prefix in {'resourceType', 'type'}): # Categorize files based on resourceType @@ -537,22 +537,24 @@ def categorize_resources(self, json_file, path, file_path, resource_types, resou except JSONError as json_error: raise JSONError(f'Failed to process {path}/{file_path}') from json_error - def collect_version_line(self, line, prefix, event, value): - if not prefix: - if event == 'start_map': - return {} - if event == 'end_map' and get(line, 'type') == 'Source Version': - self.version_lines.append(line) - elif event == 'end_map' and get(line, 'type') in ('Concept', 'Mapping') and self.isolated_version: - self.content_targets.add(Source.get_import_target(line)) - self.content_lines.append({'type': line['type'], 'id': line.get('id')}) - return line if event == 'map_key' else None - if line is not None and '.' not in prefix: - if event in ('string', 'number', 'boolean', 'null'): - line[prefix] = value - elif event in ('start_map', 'start_array'): - line[prefix] = {} if event == 'start_map' else [] - return line + def collect_seeding_line(self, builder, prefix, event, value): + """Builds each resource of a seeding import whole, for preflight to read as the importers will.""" + if not self.isolated_version: + return None + if not prefix and event == 'start_map': + builder = ijson.ObjectBuilder() + if builder is None: + return None + builder.event(event, value) + if prefix or event != 'end_map': + return builder + line = builder.value + if line.get('type') == 'Source Version': + self.version_lines.append(line) + elif line.get('type') in ('Concept', 'Mapping'): + self.content_targets.add(Source.get_import_target(line)) + self.content_lines.append({key: line.get(key) for key in IsolatedVersionCommit.CONTENT_LINE_KEYS}) + return None class ImportRequest: diff --git a/core/importers/models.py b/core/importers/models.py index f1f2d5352..990eb63e1 100644 --- a/core/importers/models.py +++ b/core/importers/models.py @@ -2,9 +2,11 @@ import time from collections import deque from datetime import datetime +from urllib.parse import unquote from celery import group from celery.utils.log import get_task_logger + from django.conf import settings from django.core.exceptions import ValidationError from django.db import transaction @@ -24,7 +26,8 @@ from core.orgs.models import Organization from core.sources.constants import ISOLATED_METADATA_FIELDS, ISOLATED_VERSION_CONTENT_FAILED, \ ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_NO_EDIT_ACCESS, SEEDED_FROM_IMPORT, \ - ISOLATED_VERSION_LARGE_DROP, ALLOW_LARGE_DROP, ISOLATED_VERSION_META_INVALID, HIERARCHY_ROOT_CANNOT_BE_DROPPED + ISOLATED_VERSION_LARGE_DROP, ALLOW_LARGE_DROP, ISOLATED_VERSION_META_INVALID, HIERARCHY_ROOT_CANNOT_BE_DROPPED, \ + ISOLATED_VERSION_DELETE_LINE from core.sources.models import Source from core.tasks.models import Task from core.users.models import UserProfile @@ -388,9 +391,25 @@ def validate_metadata(line): probe.clean_filters() if 'match_algorithms' in line: probe.clean_match_algorithms() - if probe.meta is not None and not isinstance(probe.meta, dict): + if not SourceVersionImporter.is_valid_meta(probe.meta): raise ValidationError({'meta': [ISOLATED_VERSION_META_INVALID]}) + @staticmethod + def is_valid_meta(meta): + """meta is an object, and its display.concept_filter_order, which source responses read, a list of codes.""" + if meta is None: + return True + if not isinstance(meta, dict): + return False + display = meta.get('display') + if display is None: + return True + if not isinstance(display, dict): + return False + filter_order = display.get('concept_filter_order') + return filter_order is None or ( + isinstance(filter_order, list) and all(isinstance(code, str) for code in filter_order)) + def set_head_defaults(self, source): """What the line leaves out comes from HEAD, as for POST .../versions/.""" head = source.head @@ -403,6 +422,61 @@ def set_head_defaults(self, source): source.match_algorithms = head.get_match_algorithms_for_new_version() +class MappingKeys: + """ + Which of HEAD's mappings an import's lines would update: by id, else as MappingImporter matches a line without + one, by map type and the concepts it links, or their codes and the target source. + """ + def __init__(self, ids, concept_keys, code_keys): + self.ids, self.concept_keys, self.code_keys = ids, concept_keys, code_keys + + @staticmethod + def code(value): + return unquote(str(value)) if value not in (None, '') else None + + @classmethod + def from_head(cls, head): + """mnemonic -> (concept key, code key) of each of HEAD's active mappings.""" + return { + mnemonic: ((map_type, from_id, to_id) if from_id and to_id else None, + (map_type, cls.code(from_code), cls.code(to_code), drop_version(to_source_url) or None)) + for mnemonic, map_type, from_id, to_id, from_code, to_code, to_source_url in head.mappings_set.filter( + id=F('versioned_object_id'), is_active=True).values_list( + 'mnemonic', 'map_type', 'from_concept__versioned_object_id', 'to_concept__versioned_object_id', + 'from_concept_code', 'to_concept_code', 'to_source_url') + } + + @classmethod + def from_lines(cls, lines): + ids, unnamed = set(), [] + for line in lines: + if line.get('id') not in (None, ''): + ids.add(str(line['id'])) + else: + unnamed.append(line) + urls = {drop_version(line.get(key)) for line in unnamed for key in ('from_concept_url', 'to_concept_url') + if line.get(key)} + resolved = Concept.get_versioned_objects_by_uri(urls) + concept_keys, code_keys = set(), set() + for line in unnamed: + from_url, to_url = drop_version(line.get('from_concept_url')), drop_version(line.get('to_concept_url')) + from_id, to_id = (resolved.get(from_url) or (None,))[0], (resolved.get(to_url) or (None,))[0] + if from_id and to_id: + concept_keys.add((line.get('map_type'), from_id, to_id)) + to_source_url = drop_version(line.get('to_source_url')) or (to_parent_uri(to_url) if to_url else None) + code_keys.add(( + line.get('map_type'), + cls.code(line.get('from_concept_code') or (compact(from_url.split('/'))[-1] if from_url else None)), + cls.code(line.get('to_concept_code') or (compact(to_url.split('/'))[-1] if to_url else None)), + to_source_url or None)) + return cls(ids, concept_keys, code_keys) + + def kept(self, head_mappings): + return {mnemonic for mnemonic, (concept_key, code_key) in head_mappings.items() + if mnemonic in self.ids or (concept_key and concept_key in self.concept_keys) + or code_key in self.code_keys} + + class IsolatedVersionRollback(Exception): def __init__(self, result): super().__init__(result) @@ -416,6 +490,10 @@ class IsolatedVersionCommit: any content imports. """ + CONTENT_LINE_KEYS = ( + 'type', 'id', '__action', 'owner', 'owner_type', 'source', 'map_type', 'from_concept_url', 'to_concept_url', + 'from_concept_code', 'to_concept_code', 'to_source_url') + def __init__( # pylint: disable=too-many-arguments self, version_line, user, update_if_exists=False, hierarchy_map=None, seen_concept_ids=None, seen_mapping_ids=None, content_failures=0, import_task_id=None): @@ -484,30 +562,28 @@ def preflight(self, content_lines=()): def check_planned_drop(self, head, content_lines): """ - Refuses, before any content imports, a file that leaves out HEAD's hierarchy root, or that leaves out at least - SEED_FROM_IMPORT_LARGE_DROP_MIN of HEAD's codes and more than its percent of them, unless allow_large_drop. - Mapping lines without an id are matched at import, so each is counted as keeping one of HEAD's mappings. + Refuses, before any content imports, a file with a delete line, one that leaves out HEAD's hierarchy root, or + one that leaves out at least SEED_FROM_IMPORT_LARGE_DROP_MIN of HEAD's codes and more than its percent of them, + unless allow_large_drop. A mapping line without an id keeps the HEAD mapping it would update. """ - concept_ids, mapping_ids, unnamed_mappings = set(), set(), 0 - for line in content_lines: - line_id = line.get('id') - if (line.get('type', '') or '').lower() == 'concept': - if line_id: - concept_ids.add(line_id if is_url_encoded_string(line_id) else encode_string(line_id, safe='')) - elif line_id: - mapping_ids.add(line_id) - else: - unnamed_mappings += 1 + if any((line.get('__action', '') or '').lower() == 'delete' for line in content_lines): + raise ValidationError({'__all__': [ISOLATED_VERSION_DELETE_LINE]}) + concept_lines = [line for line in content_lines if (line.get('type', '') or '').lower() == 'concept'] + mapping_lines = [line for line in content_lines if (line.get('type', '') or '').lower() == 'mapping'] + concept_ids = set() + for line in concept_lines: + if line.get('id') not in (None, ''): + line_id = str(line['id']) + concept_ids.add(line_id if is_url_encoded_string(line_id) else encode_string(line_id, safe='')) head_concepts = set(head.concepts_set.filter( id=F('versioned_object_id'), is_active=True).values_list('mnemonic', flat=True)) - head_mappings = set(head.mappings_set.filter( - id=F('versioned_object_id'), is_active=True).values_list('mnemonic', flat=True)) root_mnemonic = get(head, 'hierarchy_root.mnemonic') if root_mnemonic and root_mnemonic in head_concepts and root_mnemonic not in concept_ids: raise ValidationError({'hierarchy_root': [HIERARCHY_ROOT_CANNOT_BE_DROPPED]}) + head_mappings = MappingKeys.from_head(head) dropped = { 'concepts': len(head_concepts - concept_ids), - 'mappings': max(len(head_mappings - mapping_ids) - unnamed_mappings, 0) + 'mappings': len(head_mappings) - len(MappingKeys.from_lines(mapping_lines).kept(head_mappings)) } total = dropped['concepts'] + dropped['mappings'] if not self.allow_large_drop and total >= settings.SEED_FROM_IMPORT_LARGE_DROP_MIN and \ diff --git a/core/importers/tests.py b/core/importers/tests.py index 67b5c18f4..ed6821f58 100644 --- a/core/importers/tests.py +++ b/core/importers/tests.py @@ -51,7 +51,8 @@ from core.orgs.tests.factories import OrganizationFactory from core.sources.constants import AUTO_ID_SEQUENTIAL, AUTO_ID_UUID, ISOLATED_VERSION_CONTENT_FAILED, \ ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_NO_EDIT_ACCESS, \ - ISOLATED_VERSION_LARGE_DROP, ISOLATED_VERSION_TARGET_MISMATCH + ISOLATED_VERSION_LARGE_DROP, ISOLATED_VERSION_TARGET_MISMATCH, ISOLATED_VERSION_DELETE_LINE, \ + ISOLATED_VERSION_META_INVALID from core.sources.models import Source from core.sources.tests.factories import OrganizationSourceFactory from core.toggles.models import Toggle @@ -6914,6 +6915,100 @@ def test_plural_user_owner_type_is_read_as_the_importers_read_it(self): self.assertEqual(Source.get_import_target(users_line), ('org', 'Regen', 'LOINC')) self.assertEqual(Source.get_import_target({**users_line, 'owner_type': 'User'}), ('user', 'Regen', 'LOINC')) + @staticmethod + def unnamed_mapping(from_concept, to_concept, map_type='SAME-AS'): + line = {**IsolatedVersionImportTest.mapping('ignored', from_concept, to_concept), 'map_type': map_type} + line.pop('id') + return line + + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=10) + def test_unnamed_mappings_count_toward_the_drop(self): + concepts = [self.concept(code) for code in 'ABC'] + pairs = (('A', 'B'), ('B', 'C'), ('A', 'C')) + self.run_import([*concepts, *(self.unnamed_mapping(*pair) for pair in pairs), self.version('v1')]) + + importer = self.run_import([*concepts, *(self.unnamed_mapping(*pair) for pair in pairs), self.version('v2')]) + self.assertEqual(len(importer.failed), 0) + self.assertEqual(importer.json_result['dropped'], {'concepts': 0, 'mappings': 0}) + + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([*concepts, *(self.unnamed_mapping(*pair, map_type='NARROWER-THAN') for pair in pairs), + self.version('v3')]) + self.assertEqual(ex.exception.message_dict, {'__all__': [ISOLATED_VERSION_LARGE_DROP.format( + concepts=0, mappings=3)]}) + + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=1, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=1) + def test_numeric_ids_match_their_stored_codes(self): + self.run_import([self.concept('A'), self.concept('B'), self.mapping('3', 'A', 'B'), self.version('v1')]) + + importer = self.run_import([self.concept('A'), self.concept('B'), {**self.mapping('3', 'A', 'B'), 'id': 3}, + self.version('v2')]) + + self.assertEqual(importer.json_result['dropped'], {'concepts': 0, 'mappings': 0}) + + def test_delete_lines_are_refused(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept('A'), {**self.concept('B'), '__action': 'DELETE'}, self.version('v2')]) + + self.assertEqual(ex.exception.message_dict, {'__all__': [ISOLATED_VERSION_DELETE_LINE]}) + self.assertEqual(self.head_concepts(), {'A', 'B'}) + + def test_malformed_display_metadata_is_refused(self): + self.run_import([self.concept('A'), self.version('v1')]) + + for meta in ({'display': {'concept_filter_order': 1}}, {'display': 'x'}, ['x']): + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept('A'), self.version('v2', meta=meta)]) + self.assertEqual(ex.exception.message_dict, {'meta': [ISOLATED_VERSION_META_INVALID]}) + self.run_import([self.concept('A'), self.version('v2', meta={'display': {'concept_filter_order': ['x']}})]) + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='HEAD').concept_filter_order, ['x']) + + def test_dropped_codes_leave_heads_queries_and_bump_its_last_update(self): + self.run_import([self.concept('A'), self.concept('B'), self.mapping('M1', 'A', 'B'), self.version('v1')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + last_update = head.last_child_update + + self.run_import([self.concept('A'), self.version('v2')]) + + head.refresh_from_db() + self.assertEqual(set(head.get_concepts_queryset().values_list('mnemonic', flat=True)), {'A'}) + self.assertFalse(head.get_mappings_queryset().exists()) + self.assertGreater(head.last_child_update, last_update) + + @patch('core.sources.models.Source.sync_concept_vectors_async') + def test_semantic_change_on_head_syncs_its_vectors(self, sync_mock): + self.run_import([self.concept('A'), self.version('v1')]) + Source.objects.filter(mnemonic='LOINC', version='HEAD').update(match_algorithms=['es', 'llm']) + + self.run_import([self.concept('A'), self.version('v2', match_algorithms=['es'])]) + sync_mock.assert_called_once() + sync_mock.reset_mock() + self.run_import([self.concept('A'), self.version('v3', match_algorithms=['es'])]) + sync_mock.assert_not_called() + + def test_hierarchy_repair_links_a_child_version_url(self): + from core.common.tasks import make_hierarchy + self.run_import([self.concept('P'), self.concept('C'), self.version('v1')]) + child_version = Concept.objects.get(mnemonic='C', is_latest_version=True) + + make_hierarchy({'/orgs/Regen/sources/LOINC/concepts/P/': [child_version.uri]}) + + parent_latest = Concept.objects.get(mnemonic='P', is_latest_version=True) + self.assertTrue(HierarchicalConcepts.objects.filter(child=child_version, parent=parent_latest).exists()) + + def test_archive_preflight_reads_each_line_whole(self): + importer = Importer('task-id', '/tmp/x.zip', 'ocladmin', 'Organization', 'Regen', isolated_version=True) + content = '\n'.join(json.dumps(line) for line in [ + self.concept('A', extras={'nested': {'x': 1}}), {**self.concept('B'), '__action': 'DELETE'}, + self.version('v1', filters=['status'])]) + importer.categorize_resources( + io.BytesIO(content.encode()), 'path', 'file.json', ['Concept', 'Source Version'], {}) + + self.assertEqual(importer.version_lines[0]['filters'], ['status']) + self.assertEqual([line['__action'] for line in importer.content_lines], [None, 'DELETE']) + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=50) def test_small_drop_needs_no_confirmation(self): self.run_import([self.concept(code) for code in 'ABCDE'] + [self.version('v1')]) @@ -7165,11 +7260,33 @@ def get_child(repo_version): self.assertEqual(get_child('v2')['children'], []) self.assertFalse(get_child('v2')['has_children']) self.assertEqual(get_child('v2')['child_concepts'], []) + response = self.client.get( + '/orgs/Regen/sources/LOINC/v2/concepts/P/children/?includeChildConceptURLs=true', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.data[0]['child_concept_urls'], []) response = self.client.get( '/orgs/Regen/sources/LOINC/v1/concepts/B/parents/?includeParentConcepts=true', HTTP_AUTHORIZATION='Token ' + self.token) self.assertEqual(response.data[0]['parents'], ['/orgs/Regen/sources/LOINC/concepts/P/']) + def test_dropped_mappings_leave_head_and_newer_versions_concepts(self): + concept = IsolatedVersionImportTest.concept + version = IsolatedVersionImportTest.version + self.run_import([concept('A'), concept('B'), IsolatedVersionImportTest.mapping('M1', 'A', 'B'), version('v1')]) + self.run_import([concept('A'), concept('B'), version('v2')]) + + def get_mapping_ids(url): + response = self.client.get(url, HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.status_code, 200) + return [item['id'] for item in response.data] + + self.assertEqual(get_mapping_ids('/orgs/Regen/sources/LOINC/concepts/A/mappings/'), []) + self.assertEqual(get_mapping_ids('/orgs/Regen/sources/LOINC/v2/concepts/A/mappings/'), []) + self.assertEqual(get_mapping_ids('/orgs/Regen/sources/LOINC/v1/concepts/A/mappings/'), ['M1']) + response = self.client.get( + '/orgs/Regen/sources/LOINC/concepts/A/?includeMappings=true', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual(response.data['mappings'], []) + @patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) @patch('core.sources.models.index_source_concepts', Mock(__name__='index_source_concepts')) @@ -7247,6 +7364,11 @@ def test_zip_import_with_numeric_extras(self): self.assertEqual( Concept.objects.get(mnemonic='N3', id=F('versioned_object_id')).extras, {'rank': 1.5, 'order': 2}) + def test_import_summary_round_trips_with_or_without_drop_counts(self): + for dropped in (None, {'concepts': 1, 'mappings': 0}): + summary = ImportTaskSummary(dropped=dropped) + self.assertEqual(ImportTaskSummary(**json.loads(summary.model_dump_json())).dropped, dropped) + def test_categorize_resources_keeps_only_source_version_lines(self): importer = Importer('task-id', '/tmp/loinc.zip', 'ocladmin', 'Organization', 'Regen', isolated_version=True) resources = {} @@ -7259,7 +7381,7 @@ def test_categorize_resources_keeps_only_source_version_lines(self): '/tmp/loinc.zip', 'lines.json', ['Source', 'Source Version'], resources) self.assertEqual(importer.version_lines, [{ - **IsolatedVersionImportTest.version('v1'), 'name': 'v1', 'extras': {}}]) + **IsolatedVersionImportTest.version('v1'), 'name': 'v1', 'extras': {'a': [1]}}]) self.assertEqual( importer.validate_versioning(resources, ['Source', 'Source Version', 'Concept', 'Mapping']), ['Source', 'Concept', 'Mapping', 'Source Version']) diff --git a/core/sources/constants.py b/core/sources/constants.py index 6b8a06d47..0afec8ee8 100644 --- a/core/sources/constants.py +++ b/core/sources/constants.py @@ -26,7 +26,9 @@ ISOLATED_VERSION_TARGET_MISMATCH = \ 'Every concept and mapping in a seed_from_import import must be in the source of its Source Version line.' ALLOW_LARGE_DROP = 'allow_large_drop' -ISOLATED_VERSION_META_INVALID = 'meta must be an object.' +ISOLATED_VERSION_META_INVALID = 'meta must be an object, and meta.display.concept_filter_order a list of codes.' +ISOLATED_VERSION_DELETE_LINE = \ + 'A seed_from_import import cannot delete codes. Leave a code out of the file to drop it from HEAD.' ISOLATED_METADATA_FIELDS = ( 'description', 'full_name', 'website', 'external_id', 'canonical_url', 'identifier', 'contact', 'jurisdiction', 'publisher', 'purpose', 'copyright', 'revision_date', 'text', 'experimental', 'source_type', 'content_type', diff --git a/core/sources/models.py b/core/sources/models.py index 0fd0f8431..55cebb009 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -8,7 +8,7 @@ from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ValidationError from django.db import models, transaction -from django.db.models import UniqueConstraint, F, Max, Count +from django.db.models import UniqueConstraint, F, Max, Count, Q from django.db.models.functions import Cast from django.utils import timezone from pydash import get, compact @@ -258,6 +258,7 @@ def apply_version_metadata_to_head(self, head): self.seeded_from = {'type': SEEDED_FROM_REPO_VERSION, 'url': head.get_version_url(HEAD)} return head.seeded_from = {'type': SEEDED_FROM_REPO_VERSION, 'url': head.get_version_url(self.version)} + was_semantic = bool(head.has_semantic_match_algorithm) fields = [field for field in get(self, '_metadata_fields') or [] if field in ISOLATED_METADATA_FIELDS] for field in fields: setattr(head, field, getattr(self, field)) @@ -270,6 +271,8 @@ def apply_version_metadata_to_head(self, head): **(self.extras or {}) } head.save() + if bool(head.has_semantic_match_algorithm) != was_semantic: # as an edit of HEAD does + transaction.on_commit(lambda: head.sync_concept_vectors_async(self.created_by), robust=True) def queue_index_dropped_children(self, concept_ids, mapping_ids): """ @@ -305,6 +308,11 @@ def index_dropped_children(self, concept_ids, mapping_ids, recount=True): for model, document, ids in ((Concept, ConceptDocument, concept_ids), (Mapping, MappingDocument, mapping_ids)): for chunk in chunks(ids, DROPPED_CHILDREN_CHUNK_SIZE): self.batch_index(model.objects.filter(id__in=chunk), document) + for chunk in chunks(mapping_ids, DROPPED_CHILDREN_CHUNK_SIZE): # their concepts no longer map to the dropped + from_concepts = Mapping.objects.filter(id__in=chunk) + Concept.index_mapped_codes(Concept.objects.filter( + Q(id__in=from_concepts.values('from_concept_id')) | + Q(id__in=from_concepts.values('from_concept__versioned_object_id')))) if recount: self.update_children_counts(sync=True) @@ -324,7 +332,8 @@ def drop_unseen_children(self, seen_concept_ids, seen_mapping_ids): for chunk in chunks(sorted(ids), 5000): latest_ids = list(model.objects.filter( versioned_object_id__in=chunk, is_latest_version=True).values_list('id', flat=True)) - model.objects.filter(id__in=chunk).update(is_active=False) + # a new updated_at, so HEAD's exports and comparisons see the change + model.objects.filter(id__in=chunk).update(is_active=False, updated_at=timezone.now()) model.sources.through.objects.filter( source_id=self.id, **{f'{model.__name__.lower()}_id__in': [*chunk, *latest_ids]}).delete() if model is Concept: @@ -1334,8 +1343,8 @@ def referenced_to_sources(self): return Source.objects.filter(id__in=self.get_mappings_queryset().values_list('to_source_id', flat=True)) def get_concepts_queryset(self): - if self.is_head: - return self.concepts_set.filter(id=F('versioned_object_id')) + if self.is_head: # what an import seeding a version dropped isn't HEAD's + return self.concepts_set.filter(id=F('versioned_object_id'), is_active=True) return Concept.objects.filter( id__in=Concept.sources.through.objects.filter(source_id=self.id).values_list('concept_id', flat=True) @@ -1343,7 +1352,7 @@ def get_concepts_queryset(self): def get_mappings_queryset(self): if self.is_head: - return self.mappings_set.filter(id=F('versioned_object_id')) + return self.mappings_set.filter(id=F('versioned_object_id'), is_active=True) from core.mappings.models import Mapping return Mapping.objects.filter( From fd31cb86c08fbc021b2a463850f4f4824994f4e1 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 19 Nov 2026 13:47:54 +0530 Subject: [PATCH 6/8] OpenConceptLab/ocl_online#655 | Seeding preflight matches idless mappings as the importer does; dropped ids aren't reused, restores refresh HEAD caches, releases keep their own mappings, and parent version URLs resolve exactly --- core/common/mixins.py | 3 +- core/concepts/models.py | 41 +++++++---- core/concepts/serializers.py | 23 ++++-- core/concepts/views.py | 63 ++++++++-------- core/importers/models.py | 135 ++++++++++++++++++++++------------- core/importers/tests.py | 76 ++++++++++++++++++++ core/sources/constants.py | 1 + core/sources/models.py | 17 +++-- 8 files changed, 251 insertions(+), 108 deletions(-) diff --git a/core/common/mixins.py b/core/common/mixins.py index dbccb2d3b..1b0894d65 100644 --- a/core/common/mixins.py +++ b/core/common/mixins.py @@ -1157,7 +1157,8 @@ def restore_to_head(self): parent = versioned_object.parent if not versioned_object.is_active: versioned_object.is_active = True - versioned_object.save(update_fields=['is_active']) + # updated_at moves, so HEAD's cached comparisons and exports see it back + versioned_object.save(update_fields=['is_active', 'updated_at']) versioned_object.sources.add(parent) latest_version = versioned_object.get_latest_version() if latest_version: diff --git a/core/concepts/models.py b/core/concepts/models.py index 1ef02f113..847b7a6ce 100644 --- a/core/concepts/models.py +++ b/core/concepts/models.py @@ -1321,16 +1321,18 @@ def __get_mappings_from_relation(self, relation_manager, is_latest=False): from core.mappings.models import Mapping mappings = Mapping.objects.filter(parent_id=self.parent_id, **filters) - if is_latest: - return mappings.filter(is_latest_version=True) - return mappings.filter(id=F('versioned_object_id'), is_active=True) # not those dropped from HEAD + mappings = mappings.filter(is_latest_version=True) if is_latest else mappings.filter( + id=F('versioned_object_id')) + if self.is_versioned_object or self.is_latest_version: # HEAD's: not those dropped from it + mappings = mappings.filter(is_active=True) + return mappings def get_version_mappings(self, repo_version, include_indirect=False): """The mappings of repo_version from this concept, and with include_indirect those to it.""" criteria = Q(from_concept__versioned_object_id=self.versioned_object_id) if include_indirect: criteria |= Q(to_concept__versioned_object_id=self.versioned_object_id) - return repo_version.mappings.filter(criteria) + return repo_version.mappings.filter(criteria, is_active=True) def get_bidirectional_mappings(self): return self.get_unidirectional_mappings() | self.get_indirect_mappings() @@ -2065,9 +2067,8 @@ def __init__(self, links): def from_uri_map(cls, hierarchy_map, user=None): """hierarchy_map: child uri -> parent uris. With a user, only children it can edit and parents it can view.""" from core.sources.models import Source - # a parent URL naming one of a concept's versions links to that concept - parent_uri_of = {uri: drop_version(uri) for uris in hierarchy_map.values() for uri in uris} - resolved = Concept.get_versioned_objects_by_uri({*hierarchy_map, *parent_uri_of.values()}) + # children's URLs are versionless, so one lookup resolves them with their parents + resolved = cls.resolve_parents({*hierarchy_map, *(uri for uris in hierarchy_map.values() for uri in uris)}) editable = viewable = None if user: sources = Source.objects.filter(id__in={source_id for _, source_id in resolved.values()}) @@ -2079,10 +2080,25 @@ def from_uri_map(cls, hierarchy_map, user=None): if not child_id or (editable is not None and child_source_id not in editable): continue links.setdefault(child_id, set()).update( - resolved[parent_uri_of[uri]][0] for uri in parent_uris - if parent_uri_of[uri] in resolved and (viewable is None or resolved[parent_uri_of[uri]][1] in viewable)) + resolved[uri][0] for uri in parent_uris + if uri in resolved and (viewable is None or resolved[uri][1] in viewable)) return cls(links) + @classmethod + def resolve_parents(cls, uris): + """ + uri -> (concept id, source id) of each parent URL: the concept a URL names, or the concept of the exact version + it names. A version that doesn't exist resolves to nothing. + """ + versioned_uris = {uri for uri in uris if drop_version(uri) != uri} + versionless_uris = set(uris) - versioned_uris + resolved = Concept.get_versioned_objects_by_uri(versionless_uris) if versionless_uris else {} + for batch in chunks(sorted(versioned_uris), cls.CHUNK_SIZE): + for uri, versioned_object_id, source_id in Concept.objects.filter(uri__in=batch).values_list( + 'uri', 'versioned_object_id', 'parent_id'): + resolved[uri] = (versioned_object_id, source_id) + return resolved + @classmethod def link_child_versions(cls, version_child_map): """version_child_map: child version uri -> parent uris. Links each named row and its latest version.""" @@ -2093,9 +2109,8 @@ def link_child_versions(cls, version_child_map): for row_id, versioned_object_id, uri in Concept.objects.filter(uri__in=batch).values_list( 'id', 'versioned_object_id', 'uri'): rows[uri] = (row_id, versioned_object_id) - parent_uris = {drop_version(uri) for uris in version_child_map.values() for uri in uris} - parents = { - uri: concept_id for uri, (concept_id, _) in Concept.get_versioned_objects_by_uri(parent_uris).items()} + parents = {uri: concept_id for uri, (concept_id, _) in cls.resolve_parents( + {uri for uris in version_child_map.values() for uri in uris}).items()} latest = Concept.get_latest_version_ids_by_versioned_object_id( {*parents.values(), *(versioned_object_id for _, versioned_object_id in rows.values())}) pairs = set() @@ -2104,7 +2119,7 @@ def link_child_versions(cls, version_child_map): continue row_id, versioned_object_id = rows[child_uri] for parent_uri in uris: - parent_id = latest.get(parents.get(drop_version(parent_uri))) + parent_id = latest.get(parents.get(parent_uri)) if parent_id: pairs.add((row_id, parent_id)) if versioned_object_id in latest: diff --git a/core/concepts/serializers.py b/core/concepts/serializers.py index 8679e39ee..a33f423a8 100644 --- a/core/concepts/serializers.py +++ b/core/concepts/serializers.py @@ -255,7 +255,7 @@ def mapping_serializer_class(self): def preloads_direct_mappings(self): return 'mappings' in self.fields and self.include_direct_mappings and not ( - self.include_indirect_mappings or 'collection' in self.view_kwargs) + self.include_indirect_mappings or 'collection' in self.view_kwargs or get(self, 'context.repo_version')) def preload_page(self, instances): """Loads the direct mappings of a whole page of concepts in one go, instead of per concept.""" @@ -281,9 +281,11 @@ def preload_page(self, instances): mappings = list(mappings.order_by('id')) Mapping.load_list_fields(mappings, self.mapping_serializer_class()().fields.keys(), None, request.user) for concept in instances: + is_heads = concept.is_versioned_object or concept.is_latest_version # HEAD's leave out what it dropped concept._preloaded_mappings = [ # pylint: disable=protected-access mapping for mapping in mappings - if mapping.parent_id == concept.parent_id and mapping.from_concept_id in concept_ids[concept.id]] + if mapping.parent_id == concept.parent_id and mapping.from_concept_id in concept_ids[concept.id] + and (mapping.is_active or not is_heads)] def get_mappings(self, obj): # pylint: disable=too-many-locals from core.mappings.serializers import MappingDetailSerializer, MappingMinimalSerializer @@ -301,16 +303,23 @@ def get_mappings(self, obj): # pylint: disable=too-many-locals is_collection = 'collection' in self.view_kwargs collection_version = self.view_kwargs.get('version', HEAD) if is_collection else None parent_uri = get_collection_uri_from_view(get(context, 'view'), request) if is_collection else None + repo_version = None if is_collection else get(context, 'repo_version') # a source version's own mappings if self.include_indirect_mappings: - mappings = obj.get_bidirectional_mappings_for_collection( - parent_uri, collection_version - ) if is_collection else obj.get_bidirectional_mappings() + if repo_version: + mappings = obj.get_version_mappings(repo_version, include_indirect=True) + else: + mappings = obj.get_bidirectional_mappings_for_collection( + parent_uri, collection_version + ) if is_collection else obj.get_bidirectional_mappings() if not include_retired: mappings = mappings.filter(retired=False) return serializer_class(mappings.order_by('id'), many=True).data if self.include_direct_mappings: - mappings = obj.get_unidirectional_mappings_for_collection( - parent_uri, collection_version) if is_collection else obj.get_unidirectional_mappings() + if repo_version: + mappings = obj.get_version_mappings(repo_version) + else: + mappings = obj.get_unidirectional_mappings_for_collection( + parent_uri, collection_version) if is_collection else obj.get_unidirectional_mappings() if map_types: mappings = mappings.filter(map_type__in=map_types) if target_repo_urls: diff --git a/core/concepts/views.py b/core/concepts/views.py index bcdcfc14d..a5d9629f6 100644 --- a/core/concepts/views.py +++ b/core/concepts/views.py @@ -357,7 +357,38 @@ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) -class ConceptRetrieveUpdateDestroyView(ConceptBaseView, RetrieveAPIView, UpdateAPIView, DestroyAPIView): +class ConceptHierarchyMixin: + def get_source_version(self): + """The source version named in the URL, or None for HEAD and collection URLs.""" + if '_source_version' not in self.__dict__: + self._source_version = self.find_source_version() + return self._source_version + + def find_source_version(self): + source, version = self.kwargs.get('source'), self.kwargs.get('version') + if not source or not version or version == HEAD: + return None + from core.sources.models import Source + if 'org' in self.kwargs: + filters = {'organization__mnemonic': self.kwargs['org']} + else: + filters = {'user__username': self.request.user.username if self.user_is_self else self.kwargs.get('user')} + if version == LATEST: + return Source.find_latest_released_version_by({**filters, 'mnemonic': source}) + return Source.get_version(source, version, filters) + + def get_serializer_context(self): + return {**super().get_serializer_context(), 'repo_version': self.get_source_version()} + + def get_hierarchy_queryset(self, instance, relation): + repo_version = self.get_source_version() + if repo_version: + return instance.get_version_hierarchy_queryset(relation, repo_version) + return instance.get_hierarchy_related_queryset(relation) + + +class ConceptRetrieveUpdateDestroyView(ConceptHierarchyMixin, ConceptBaseView, RetrieveAPIView, UpdateAPIView, + DestroyAPIView): serializer_class = ConceptDetailSerializer def is_container_version_specified(self): @@ -602,36 +633,6 @@ def get_clone_to_source(self): return source -class ConceptHierarchyMixin: - def get_source_version(self): - """The source version named in the URL, or None for HEAD and collection URLs.""" - if '_source_version' not in self.__dict__: - self._source_version = self.find_source_version() - return self._source_version - - def find_source_version(self): - source, version = self.kwargs.get('source'), self.kwargs.get('version') - if not source or not version or version == HEAD: - return None - from core.sources.models import Source - if 'org' in self.kwargs: - filters = {'organization__mnemonic': self.kwargs['org']} - else: - filters = {'user__username': self.request.user.username if self.user_is_self else self.kwargs.get('user')} - if version == LATEST: - return Source.find_latest_released_version_by({**filters, 'mnemonic': source}) - return Source.get_version(source, version, filters) - - def get_serializer_context(self): - return {**super().get_serializer_context(), 'repo_version': self.get_source_version()} - - def get_hierarchy_queryset(self, instance, relation): - repo_version = self.get_source_version() - if repo_version: - return instance.get_version_hierarchy_queryset(relation, repo_version) - return instance.get_hierarchy_related_queryset(relation) - - class ConceptChildrenView(ConceptHierarchyMixin, ConceptBaseView, ListWithHeadersMixin): is_page_size_capped = True is_searchable = False # a search would list the repo's concepts, not this concept's hierarchy diff --git a/core/importers/models.py b/core/importers/models.py index 990eb63e1..c111d5c2d 100644 --- a/core/importers/models.py +++ b/core/importers/models.py @@ -2,7 +2,6 @@ import time from collections import deque from datetime import datetime -from urllib.parse import unquote from celery import group from celery.utils.log import get_task_logger @@ -27,7 +26,7 @@ from core.sources.constants import ISOLATED_METADATA_FIELDS, ISOLATED_VERSION_CONTENT_FAILED, \ ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_NO_EDIT_ACCESS, SEEDED_FROM_IMPORT, \ ISOLATED_VERSION_LARGE_DROP, ALLOW_LARGE_DROP, ISOLATED_VERSION_META_INVALID, HIERARCHY_ROOT_CANNOT_BE_DROPPED, \ - ISOLATED_VERSION_DELETE_LINE + ISOLATED_VERSION_DELETE_LINE, ISOLATED_VERSION_LIST_FIELD_INVALID from core.sources.models import Source from core.tasks.models import Task from core.users.models import UserProfile @@ -386,6 +385,9 @@ def validate_metadata(line): The checks a source's save runs, on the metadata a version line sets; persisting a version skips them. Values a version takes from HEAD aren't checked again. """ + for field in ('properties', 'filters', 'match_algorithms'): + if line.get(field) is not None and not isinstance(line[field], list): + raise ValidationError({field: [ISOLATED_VERSION_LIST_FIELD_INVALID.format(field=field)]}) probe = Source(**{field: line[field] for field in ISOLATED_METADATA_FIELDS if field in line}) probe.clean_properties() probe.clean_filters() @@ -422,59 +424,91 @@ def set_head_defaults(self, source): source.match_algorithms = head.get_match_algorithms_for_new_version() -class MappingKeys: +class MappingMatcher: """ - Which of HEAD's mappings an import's lines would update: by id, else as MappingImporter matches a line without - one, by map type and the concepts it links, or their codes and the target source. + Which of HEAD's mappings an import's lines would update, found as MappingImporter finds them: by id, else by map + type, the from concept or code, and the target concept, code or source the line names. Of several matches, the + importer updates the first one not retired, else the newest. """ - def __init__(self, ids, concept_keys, code_keys): - self.ids, self.concept_keys, self.code_keys = ids, concept_keys, code_keys + FIELDS = ('id', 'mnemonic', 'retired', 'is_active', 'map_type', 'from_concept__versioned_object_id', + 'from_concept_code', 'to_concept__versioned_object_id', 'to_concept_code', 'to_source_url', + 'to_source__uri') + + def __init__(self, head): + self.rows, self.by_mnemonic, self.by_from_id, self.by_from_code = {}, {}, {}, {} + for row in head.mappings_set.filter(id=F('versioned_object_id')).values(*self.FIELDS): + self.rows[row['id']] = row + self.by_mnemonic[row['mnemonic']] = row['id'] + from_key = (row['map_type'], row['from_concept__versioned_object_id']) + self.by_from_id.setdefault(from_key, []).append(row['id']) + self.by_from_code.setdefault((row['map_type'], row['from_concept_code']), []).append(row['id']) - @staticmethod - def code(value): - return unquote(str(value)) if value not in (None, '') else None + @property + def active_ids(self): + return {row_id for row_id, row in self.rows.items() if row['is_active']} - @classmethod - def from_head(cls, head): - """mnemonic -> (concept key, code key) of each of HEAD's active mappings.""" - return { - mnemonic: ((map_type, from_id, to_id) if from_id and to_id else None, - (map_type, cls.code(from_code), cls.code(to_code), drop_version(to_source_url) or None)) - for mnemonic, map_type, from_id, to_id, from_code, to_code, to_source_url in head.mappings_set.filter( - id=F('versioned_object_id'), is_active=True).values_list( - 'mnemonic', 'map_type', 'from_concept__versioned_object_id', 'to_concept__versioned_object_id', - 'from_concept_code', 'to_concept_code', 'to_source_url') - } + @staticmethod + def variations(code): + code = str(code) + return {*Concept.get_encoded_str_variations(code), code.replace(' ', '+')} - @classmethod - def from_lines(cls, lines): - ids, unnamed = set(), [] + @staticmethod + def last_segment(url): + return compact(url.split('/'))[-1] + + def kept(self, lines): + """The ids of HEAD's active mappings these lines would update.""" + unnamed = [line for line in lines if line.get('id') in (None, '')] + concept_urls = {drop_version(line.get(key)) for line in unnamed + for key in ('from_concept_url', 'to_concept_url') if line.get(key)} + resolved = {uri: concept_id for uri, (concept_id, _) in Concept.get_versioned_objects_by_uri( + concept_urls).items()} + source_uris = {to_parent_uri(drop_version(line['to_concept_url'])) for line in unnamed + if line.get('to_concept_url') and not line.get('to_source_url')} + existing_sources = set(Source.objects.filter(uri__in=source_uris).values_list('uri', flat=True)) + kept = set() for line in lines: if line.get('id') not in (None, ''): - ids.add(str(line['id'])) + row_id = self.by_mnemonic.get(str(line['id'])) + else: + row_id = self.choose(self.get_candidates(line, resolved, existing_sources)) + if row_id and self.rows[row_id]['is_active']: + kept.add(row_id) + return kept + + def get_candidates(self, line, resolved, existing_sources): # pylint: disable=too-many-locals + map_type, from_code = line.get('map_type'), line.get('from_concept_code') + from_url = drop_version(line.get('from_concept_url') or '') + from_id = resolved.get(from_url) + if from_id: + candidates = self.by_from_id.get((map_type, from_id), []) + else: + codes = self.variations(from_code) if from_code else {self.last_segment(from_url)} if from_url else set() + candidates = [row_id for code in codes for row_id in self.by_from_code.get((map_type, code), [])] + checks = [] + if from_code and from_id: + checks.append(lambda row: row['from_concept_code'] in self.variations(from_code)) + to_url, to_code, to_source_url = drop_version(line.get('to_concept_url') or ''), line.get( + 'to_concept_code'), line.get('to_source_url') + if to_url: + to_id = resolved.get(to_url) + if to_id: + checks.append(lambda row: row['to_concept__versioned_object_id'] == to_id) else: - unnamed.append(line) - urls = {drop_version(line.get(key)) for line in unnamed for key in ('from_concept_url', 'to_concept_url') - if line.get(key)} - resolved = Concept.get_versioned_objects_by_uri(urls) - concept_keys, code_keys = set(), set() - for line in unnamed: - from_url, to_url = drop_version(line.get('from_concept_url')), drop_version(line.get('to_concept_url')) - from_id, to_id = (resolved.get(from_url) or (None,))[0], (resolved.get(to_url) or (None,))[0] - if from_id and to_id: - concept_keys.add((line.get('map_type'), from_id, to_id)) - to_source_url = drop_version(line.get('to_source_url')) or (to_parent_uri(to_url) if to_url else None) - code_keys.add(( - line.get('map_type'), - cls.code(line.get('from_concept_code') or (compact(from_url.split('/'))[-1] if from_url else None)), - cls.code(line.get('to_concept_code') or (compact(to_url.split('/'))[-1] if to_url else None)), - to_source_url or None)) - return cls(ids, concept_keys, code_keys) - - def kept(self, head_mappings): - return {mnemonic for mnemonic, (concept_key, code_key) in head_mappings.items() - if mnemonic in self.ids or (concept_key and concept_key in self.concept_keys) - or code_key in self.code_keys} + checks.append(lambda row: row['to_concept_code'] == self.last_segment(to_url)) + if not to_source_url and to_parent_uri(to_url) in existing_sources: + checks.append(lambda row: row['to_source__uri'] == to_parent_uri(to_url)) + if to_source_url: + checks.append(lambda row: row['to_source_url'] == drop_version(to_source_url)) + if to_code: + checks.append(lambda row: row['to_concept_code'] in self.variations(to_code)) + return [row_id for row_id in dict.fromkeys(candidates) if all(check(self.rows[row_id]) for check in checks)] + + def choose(self, candidates): + if len(candidates) <= 1: + return candidates[0] if candidates else None + not_retired = [row_id for row_id in candidates if not self.rows[row_id]['retired']] + return min(not_retired) if not_retired else max(candidates) class IsolatedVersionRollback(Exception): @@ -564,7 +598,7 @@ def check_planned_drop(self, head, content_lines): """ Refuses, before any content imports, a file with a delete line, one that leaves out HEAD's hierarchy root, or one that leaves out at least SEED_FROM_IMPORT_LARGE_DROP_MIN of HEAD's codes and more than its percent of them, - unless allow_large_drop. A mapping line without an id keeps the HEAD mapping it would update. + unless allow_large_drop. A mapping line without an id keeps the one HEAD mapping it would update. """ if any((line.get('__action', '') or '').lower() == 'delete' for line in content_lines): raise ValidationError({'__all__': [ISOLATED_VERSION_DELETE_LINE]}) @@ -580,10 +614,11 @@ def check_planned_drop(self, head, content_lines): root_mnemonic = get(head, 'hierarchy_root.mnemonic') if root_mnemonic and root_mnemonic in head_concepts and root_mnemonic not in concept_ids: raise ValidationError({'hierarchy_root': [HIERARCHY_ROOT_CANNOT_BE_DROPPED]}) - head_mappings = MappingKeys.from_head(head) + matcher = MappingMatcher(head) + head_mappings = matcher.active_ids dropped = { 'concepts': len(head_concepts - concept_ids), - 'mappings': len(head_mappings) - len(MappingKeys.from_lines(mapping_lines).kept(head_mappings)) + 'mappings': len(head_mappings - matcher.kept(mapping_lines)) } total = dropped['concepts'] + dropped['mappings'] if not self.allow_large_drop and total >= settings.SEED_FROM_IMPORT_LARGE_DROP_MIN and \ diff --git a/core/importers/tests.py b/core/importers/tests.py index ed6821f58..da30cc4ff 100644 --- a/core/importers/tests.py +++ b/core/importers/tests.py @@ -6937,6 +6937,76 @@ def test_unnamed_mappings_count_toward_the_drop(self): self.assertEqual(ex.exception.message_dict, {'__all__': [ISOLATED_VERSION_LARGE_DROP.format( concepts=0, mappings=3)]}) + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=2, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=10) + def test_unnamed_mapping_keeps_only_the_mapping_the_importer_updates(self): + concepts = [self.concept(code) for code in 'ABC'] + pairs = (('A', 'B'), ('B', 'C'), ('A', 'C')) + self.run_import([*concepts, *( + line for index, pair in enumerate(pairs) for line in ( + {**self.mapping(f'R{index}', *pair), 'retired': True}, self.mapping(f'M{index}', *pair))), + self.version('v1')]) + + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([*concepts, *(self.unnamed_mapping(*pair) for pair in pairs), self.version('v2')]) + + self.assertEqual(ex.exception.message_dict, {'__all__': [ISOLATED_VERSION_LARGE_DROP.format( + concepts=0, mappings=3)]}) + + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=1, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=10) + def test_unnamed_mapping_naming_its_target_by_code_keeps_it(self): + concepts = [self.concept(code) for code in 'ABC'] + pairs = (('A', 'B'), ('B', 'C'), ('A', 'C')) + self.run_import([*concepts, *(self.mapping(f'M{index}', *pair) for index, pair in enumerate(pairs)), + self.version('v1')]) + lines = [] + for from_concept, to_concept in pairs: + line = self.unnamed_mapping(from_concept, to_concept) + line.pop('to_concept_url') + lines.append({**line, 'to_concept_code': to_concept}) + + importer = self.run_import([*concepts, *lines, self.version('v2')]) + + self.assertEqual(importer.json_result['dropped'], {'concepts': 0, 'mappings': 0}) + + def test_new_ids_skip_those_of_dropped_codes(self): + self.run_import([self.concept('A'), self.concept('B'), self.mapping('1', 'A', 'B'), self.mapping('2', 'B', 'A'), + self.version('v1')]) + self.run_import([self.concept('A'), self.concept('B'), self.mapping('1', 'A', 'B'), self.version('v2')]) + + self.run_import([self.unnamed_mapping('A', 'A')], isolated_version=False) + + new = Mapping.objects.get(parent__mnemonic='LOINC', id=F('versioned_object_id'), from_concept__mnemonic='A', + to_concept__mnemonic='A') + self.assertNotIn(new.mnemonic, ('1', '2')) + + def test_restoring_a_dropped_code_moves_heads_last_update(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + self.run_import([self.concept('A'), self.version('v2')]) + head = Source.objects.get(mnemonic='LOINC', version='HEAD') + last_update = head.last_child_update + + self.run_import([self.concept('B')], isolated_version=False) + + self.assertEqual(self.head_concepts(), {'A', 'B'}) + self.assertGreater(Source.objects.get(id=head.id).last_child_update, last_update) + + def test_list_valued_metadata_must_be_lists(self): + self.run_import([self.concept('A'), self.version('v1')]) + + for field in ('properties', 'filters', 'match_algorithms'): + with self.assertRaises(DjangoValidationError) as ex: + self.run_import([self.concept('A'), self.version('v2', **{field: 5})]) + self.assertEqual(ex.exception.message_dict, {field: [f'{field} must be a list.']}) + + def test_hierarchy_repair_ignores_a_parent_version_that_does_not_exist(self): + from core.common.tasks import make_hierarchy + self.run_import([self.concept('P'), self.concept('C'), self.version('v1')]) + child_version = Concept.objects.get(mnemonic='C', is_latest_version=True) + + make_hierarchy({'/orgs/Regen/sources/LOINC/concepts/P/999999/': [child_version.uri]}) + + self.assertFalse(HierarchicalConcepts.objects.filter(child__mnemonic='C').exists()) + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=1, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=1) def test_numeric_ids_match_their_stored_codes(self): self.run_import([self.concept('A'), self.concept('B'), self.mapping('3', 'A', 'B'), self.version('v1')]) @@ -7286,6 +7356,12 @@ def get_mapping_ids(url): response = self.client.get( '/orgs/Regen/sources/LOINC/concepts/A/?includeMappings=true', HTTP_AUTHORIZATION='Token ' + self.token) self.assertEqual(response.data['mappings'], []) + response = self.client.get( + '/orgs/Regen/sources/LOINC/v1/concepts/A/?includeMappings=true', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual([item['id'] for item in response.data['mappings']], ['M1']) + + Source.objects.get(mnemonic='LOINC', version='v1').mappings.update(is_active=False) # an admin soft-delete + self.assertEqual(get_mapping_ids('/orgs/Regen/sources/LOINC/v1/concepts/A/mappings/'), []) @patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) diff --git a/core/sources/constants.py b/core/sources/constants.py index 0afec8ee8..d6c87ea7b 100644 --- a/core/sources/constants.py +++ b/core/sources/constants.py @@ -27,6 +27,7 @@ 'Every concept and mapping in a seed_from_import import must be in the source of its Source Version line.' ALLOW_LARGE_DROP = 'allow_large_drop' ISOLATED_VERSION_META_INVALID = 'meta must be an object, and meta.display.concept_filter_order a list of codes.' +ISOLATED_VERSION_LIST_FIELD_INVALID = '{field} must be a list.' ISOLATED_VERSION_DELETE_LINE = \ 'A seed_from_import import cannot delete codes. Leave a code out of the file to drop it from HEAD.' ISOLATED_METADATA_FIELDS = ( diff --git a/core/sources/models.py b/core/sources/models.py index 55cebb009..ff3624c89 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -308,11 +308,11 @@ def index_dropped_children(self, concept_ids, mapping_ids, recount=True): for model, document, ids in ((Concept, ConceptDocument, concept_ids), (Mapping, MappingDocument, mapping_ids)): for chunk in chunks(ids, DROPPED_CHILDREN_CHUNK_SIZE): self.batch_index(model.objects.filter(id__in=chunk), document) - for chunk in chunks(mapping_ids, DROPPED_CHILDREN_CHUNK_SIZE): # their concepts no longer map to the dropped - from_concepts = Mapping.objects.filter(id__in=chunk) + for chunk in chunks(mapping_ids, DROPPED_CHILDREN_CHUNK_SIZE): + # the rows that serve HEAD no longer map to the dropped; older releases' rows keep their codes + from_concept_ids = Mapping.objects.filter(id__in=chunk).values('from_concept__versioned_object_id') Concept.index_mapped_codes(Concept.objects.filter( - Q(id__in=from_concepts.values('from_concept_id')) | - Q(id__in=from_concepts.values('from_concept__versioned_object_id')))) + Q(id__in=from_concept_ids) | Q(versioned_object_id__in=from_concept_ids, is_latest_version=True))) if recount: self.update_children_counts(sync=True) @@ -1022,10 +1022,15 @@ def get_max_mapping_attribute(self, attribute): return get(self.get_mappings_queryset().aggregate(max_val=Max(attribute)), 'max_val', None) def get_max_concept_mnemonic(self): - return self.get_max_mnemonic_for_resource(self.get_concepts_queryset()) + # over every concept HEAD has had, so a dropped one's id isn't given out again + queryset = self.concepts_set.filter( + id=F('versioned_object_id')) if self.is_head else self.get_concepts_queryset() + return self.get_max_mnemonic_for_resource(queryset) def get_max_mapping_mnemonic(self): - return self.get_max_mnemonic_for_resource(self.get_mappings_queryset()) + queryset = self.mappings_set.filter( + id=F('versioned_object_id')) if self.is_head else self.get_mappings_queryset() + return self.get_max_mnemonic_for_resource(queryset) @staticmethod def get_max_mnemonic_for_resource(queryset): From f027af055a1d19134adcb08ed13177a0969eb2c1 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 19 Nov 2026 15:03:40 +0530 Subject: [PATCH 7/8] OpenConceptLab/ocl_online#655 | Seeding needs update_if_exists and matches from codes as the importer does; release concept lists and older concept versions use the release's own mappings; latest-as-HEAD reads HEAD --- core/concepts/documents.py | 2 +- core/concepts/models.py | 12 +++ core/concepts/serializers.py | 41 +++++---- core/concepts/views.py | 63 +++++++------- core/importers/models.py | 15 ++-- core/importers/tests.py | 102 ++++++++++++++++++++++- core/importers/views.py | 3 + core/integration_tests/tests_concepts.py | 2 + core/mappings/serializers.py | 5 ++ core/sources/constants.py | 1 + core/sources/models.py | 4 +- 11 files changed, 193 insertions(+), 57 deletions(-) diff --git a/core/concepts/documents.py b/core/concepts/documents.py index 10aebfce3..0e936bcfd 100644 --- a/core/concepts/documents.py +++ b/core/concepts/documents.py @@ -309,7 +309,7 @@ def add_vectors(self, data, instance, name, preferred_locale, synonyms): # pyli @staticmethod def get_mapped_codes(instance): - mappings = instance.get_unidirectional_mappings() + mappings = instance.get_indexed_mappings() same_as_mapped_codes = [] other_mapped_codes = [] verbose_info = [] diff --git a/core/concepts/models.py b/core/concepts/models.py index 847b7a6ce..ccd87fcfc 100644 --- a/core/concepts/models.py +++ b/core/concepts/models.py @@ -1334,6 +1334,18 @@ def get_version_mappings(self, repo_version, include_indirect=False): criteria |= Q(to_concept__versioned_object_id=self.versioned_object_id) return repo_version.mappings.filter(criteria, is_active=True) + def get_indexed_mappings(self): + """ + The mappings this row's search document takes its mapped codes from: HEAD's for a row HEAD serves, else those + of the releases the row is in. + """ + if self.is_versioned_object or self.is_latest_version or not self.id: + return self.get_unidirectional_mappings() + from core.mappings.models import Mapping + return Mapping.objects.filter( + sources__in=self.sources.all(), from_concept__versioned_object_id=self.versioned_object_id, is_active=True + ).distinct() + def get_bidirectional_mappings(self): return self.get_unidirectional_mappings() | self.get_indirect_mappings() diff --git a/core/concepts/serializers.py b/core/concepts/serializers.py index a33f423a8..fa3875a7c 100644 --- a/core/concepts/serializers.py +++ b/core/concepts/serializers.py @@ -248,14 +248,16 @@ def get_references(self, obj): return None def mapping_serializer_class(self): - from core.mappings.serializers import MappingDetailSerializer, MappingMinimalSerializer + from core.mappings.serializers import MappingDetailSerializer, MappingMinimalSerializer, \ + EmbeddedMappingMinimalSerializer request = get(self, 'context.request') - is_mapping_brief = request.query_params.get('mappingBrief', None) in TRUTHY - return MappingMinimalSerializer if is_mapping_brief else MappingDetailSerializer + if request.query_params.get('mappingBrief', None) not in TRUTHY: + return MappingDetailSerializer + return EmbeddedMappingMinimalSerializer if get(self, 'context.repo_version') else MappingMinimalSerializer def preloads_direct_mappings(self): return 'mappings' in self.fields and self.include_direct_mappings and not ( - self.include_indirect_mappings or 'collection' in self.view_kwargs or get(self, 'context.repo_version')) + self.include_indirect_mappings or 'collection' in self.view_kwargs) def preload_page(self, instances): """Loads the direct mappings of a whole page of concepts in one go, instead of per concept.""" @@ -264,14 +266,21 @@ def preload_page(self, instances): return from core.mappings.models import Mapping params = request.query_params - concept_ids = { - concept.id: set(compact([ - concept.id, concept.versioned_object_id, get(concept.get_latest_version(), 'id')])) - for concept in instances - } - mappings = Mapping.objects.filter( - parent_id__in={concept.parent_id for concept in instances}, - from_concept_id__in=set().union(*concept_ids.values()), id=F('versioned_object_id')) + repo_version = get(self, 'context.repo_version') + if repo_version: # a source version's own mappings + versioned_object_ids = {concept.versioned_object_id for concept in instances} + mappings = repo_version.mappings.filter( + is_active=True, from_concept__versioned_object_id__in=versioned_object_ids + ).annotate(from_versioned_object_id=F('from_concept__versioned_object_id')) + else: + concept_ids = { + concept.id: set(compact([ + concept.id, concept.versioned_object_id, get(concept.get_latest_version(), 'id')])) + for concept in instances + } + mappings = Mapping.objects.filter( + parent_id__in={concept.parent_id for concept in instances}, + from_concept_id__in=set().union(*concept_ids.values()), id=F('versioned_object_id')) if map_types := compact((params.get('mapTypes', '') or '').split(',')): mappings = mappings.filter(map_type__in=map_types) if target_repo_urls := compact((params.get('targetRepoUrls', '') or '').split(',')): @@ -281,6 +290,10 @@ def preload_page(self, instances): mappings = list(mappings.order_by('id')) Mapping.load_list_fields(mappings, self.mapping_serializer_class()().fields.keys(), None, request.user) for concept in instances: + if repo_version: + concept._preloaded_mappings = [ # pylint: disable=protected-access + mapping for mapping in mappings if mapping.from_versioned_object_id == concept.versioned_object_id] + continue is_heads = concept.is_versioned_object or concept.is_latest_version # HEAD's leave out what it dropped concept._preloaded_mappings = [ # pylint: disable=protected-access mapping for mapping in mappings @@ -288,18 +301,16 @@ def preload_page(self, instances): and (mapping.is_active or not is_heads)] def get_mappings(self, obj): # pylint: disable=too-many-locals - from core.mappings.serializers import MappingDetailSerializer, MappingMinimalSerializer context = get(self, 'context') request = get(context, 'request') preloaded = getattr(obj, '_preloaded_mappings', None) if preloaded is not None and self.preloads_direct_mappings(): child = self.mapping_serializer_class()() return [child.to_representation(mapping) for mapping in preloaded] - is_mapping_brief = request.query_params.get('mappingBrief', None) in TRUTHY map_types = compact((request.query_params.get('mapTypes', '') or '').split(',')) target_repo_urls = compact((request.query_params.get('targetRepoUrls', '') or '').split(',')) include_retired = request.query_params.get(INCLUDE_RETIRED_PARAM, None) in TRUTHY - serializer_class = MappingMinimalSerializer if is_mapping_brief else MappingDetailSerializer + serializer_class = self.mapping_serializer_class() is_collection = 'collection' in self.view_kwargs collection_version = self.view_kwargs.get('version', HEAD) if is_collection else None parent_uri = get_collection_uri_from_view(get(context, 'view'), request) if is_collection else None diff --git a/core/concepts/views.py b/core/concepts/views.py index a5d9629f6..8b6a28827 100644 --- a/core/concepts/views.py +++ b/core/concepts/views.py @@ -175,7 +175,38 @@ def get_queryset(self): raise Http404() -class ConceptListView(ConceptBaseView, ListWithHeadersMixin, CreateModelMixin): +class ConceptHierarchyMixin: + def get_source_version(self): + """The source version named in the URL, or None for HEAD (latest included, when it is HEAD) and collections.""" + if '_source_version' not in self.__dict__: + repo_version = self.find_source_version() + self._source_version = None if get(repo_version, 'is_head') else repo_version + return self._source_version + + def find_source_version(self): + source, version = self.kwargs.get('source'), self.kwargs.get('version') + if not source or not version or version == HEAD: + return None + from core.sources.models import Source + if 'org' in self.kwargs: + filters = {'organization__mnemonic': self.kwargs['org']} + else: + filters = {'user__username': self.request.user.username if self.user_is_self else self.kwargs.get('user')} + if version == LATEST: + return Source.find_latest_released_version_by({**filters, 'mnemonic': source}) + return Source.get_version(source, version, filters) + + def get_serializer_context(self): + return {**super().get_serializer_context(), 'repo_version': self.get_source_version()} + + def get_hierarchy_queryset(self, instance, relation): + repo_version = self.get_source_version() + if repo_version: + return instance.get_version_hierarchy_queryset(relation, repo_version) + return instance.get_hierarchy_related_queryset(relation) + + +class ConceptListView(ConceptHierarchyMixin, ConceptBaseView, ListWithHeadersMixin, CreateModelMixin): is_page_size_capped = True serializer_class = ConceptListSerializer @@ -357,36 +388,6 @@ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) -class ConceptHierarchyMixin: - def get_source_version(self): - """The source version named in the URL, or None for HEAD and collection URLs.""" - if '_source_version' not in self.__dict__: - self._source_version = self.find_source_version() - return self._source_version - - def find_source_version(self): - source, version = self.kwargs.get('source'), self.kwargs.get('version') - if not source or not version or version == HEAD: - return None - from core.sources.models import Source - if 'org' in self.kwargs: - filters = {'organization__mnemonic': self.kwargs['org']} - else: - filters = {'user__username': self.request.user.username if self.user_is_self else self.kwargs.get('user')} - if version == LATEST: - return Source.find_latest_released_version_by({**filters, 'mnemonic': source}) - return Source.get_version(source, version, filters) - - def get_serializer_context(self): - return {**super().get_serializer_context(), 'repo_version': self.get_source_version()} - - def get_hierarchy_queryset(self, instance, relation): - repo_version = self.get_source_version() - if repo_version: - return instance.get_version_hierarchy_queryset(relation, repo_version) - return instance.get_hierarchy_related_queryset(relation) - - class ConceptRetrieveUpdateDestroyView(ConceptHierarchyMixin, ConceptBaseView, RetrieveAPIView, UpdateAPIView, DestroyAPIView): serializer_class = ConceptDetailSerializer diff --git a/core/importers/models.py b/core/importers/models.py index c111d5c2d..23c5dd09c 100644 --- a/core/importers/models.py +++ b/core/importers/models.py @@ -26,7 +26,7 @@ from core.sources.constants import ISOLATED_METADATA_FIELDS, ISOLATED_VERSION_CONTENT_FAILED, \ ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_NO_EDIT_ACCESS, SEEDED_FROM_IMPORT, \ ISOLATED_VERSION_LARGE_DROP, ALLOW_LARGE_DROP, ISOLATED_VERSION_META_INVALID, HIERARCHY_ROOT_CANNOT_BE_DROPPED, \ - ISOLATED_VERSION_DELETE_LINE, ISOLATED_VERSION_LIST_FIELD_INVALID + ISOLATED_VERSION_DELETE_LINE, ISOLATED_VERSION_LIST_FIELD_INVALID, SEED_FROM_IMPORT_NEEDS_UPDATE from core.sources.models import Source from core.tasks.models import Task from core.users.models import UserProfile @@ -428,7 +428,7 @@ class MappingMatcher: """ Which of HEAD's mappings an import's lines would update, found as MappingImporter finds them: by id, else by map type, the from concept or code, and the target concept, code or source the line names. Of several matches, the - importer updates the first one not retired, else the newest. + importer updates the first one not retired, else the newest, with the lines before it already applied. """ FIELDS = ('id', 'mnemonic', 'retired', 'is_active', 'map_type', 'from_concept__versioned_object_id', 'from_concept_code', 'to_concept__versioned_object_id', 'to_concept_code', 'to_source_url', @@ -472,8 +472,11 @@ def kept(self, lines): row_id = self.by_mnemonic.get(str(line['id'])) else: row_id = self.choose(self.get_candidates(line, resolved, existing_sources)) - if row_id and self.rows[row_id]['is_active']: - kept.add(row_id) + if row_id: + # a seeding import leaves a field it doesn't send at its default, so the next line sees this + self.rows[row_id]['retired'] = line.get('retired') in (True, 'true', 'True') + if self.rows[row_id]['is_active']: + kept.add(row_id) return kept def get_candidates(self, line, resolved, existing_sources): # pylint: disable=too-many-locals @@ -583,6 +586,8 @@ def preflight(self, content_lines=()): Runs before any content imports, so a version that would be rejected leaves HEAD untouched. content_lines are the import's Concept and Mapping lines, for what HEAD would lose. """ + if not self.update_if_exists: + raise ValidationError({'__all__': [SEED_FROM_IMPORT_NEEDS_UPDATE]}) importer = SourceVersionImporter({**self.version_line}, self.user, self.update_if_exists, isolated_version=True) rejected, result = self.get_rejection(importer, needs_head=False) if rejected: @@ -909,7 +914,7 @@ def get_queryset(self): # pylint: disable=too-many-branches 'map_type': self.get('map_type'), } if from_concept_code: - filters['from_concept_code'] = [ + filters['from_concept_code__in'] = [ *Concept.get_encoded_str_variations(from_concept_code), from_concept_code.replace(' ', '+') ] diff --git a/core/importers/tests.py b/core/importers/tests.py index da30cc4ff..42874f209 100644 --- a/core/importers/tests.py +++ b/core/importers/tests.py @@ -52,7 +52,7 @@ from core.sources.constants import AUTO_ID_SEQUENTIAL, AUTO_ID_UUID, ISOLATED_VERSION_CONTENT_FAILED, \ ISOLATED_VERSION_EXISTS, ISOLATED_VERSION_LINE_INVALID, ISOLATED_VERSION_NO_EDIT_ACCESS, \ ISOLATED_VERSION_LARGE_DROP, ISOLATED_VERSION_TARGET_MISMATCH, ISOLATED_VERSION_DELETE_LINE, \ - ISOLATED_VERSION_META_INVALID + ISOLATED_VERSION_META_INVALID, SEED_FROM_IMPORT_NEEDS_UPDATE from core.sources.models import Source from core.sources.tests.factories import OrganizationSourceFactory from core.toggles.models import Toggle @@ -6647,10 +6647,10 @@ def test_preflight_rejects_a_version_before_content_imports(self): (self.version('v2'), ISOLATED_VERSION_NO_EDIT_ACCESS), ): with self.assertRaises(DjangoValidationError) as context: - IsolatedVersionCommit(line, user).preflight() + IsolatedVersionCommit(line, user, True).preflight() self.assertEqual(context.exception.message_dict, {'__all__': [message]}) self.assertIsNone(IsolatedVersionCommit( - {**self.version('v2'), 'source': 'NEW'}, UserProfile.objects.get(username='ocladmin')).preflight()) + {**self.version('v2'), 'source': 'NEW'}, UserProfile.objects.get(username='ocladmin'), True).preflight()) @patch('core.sources.models.Source.batch_index', side_effect=Exception('ES down')) def test_failed_search_update_does_not_undo_a_committed_version(self, batch_index_mock): @@ -6968,6 +6968,70 @@ def test_unnamed_mapping_naming_its_target_by_code_keeps_it(self): self.assertEqual(importer.json_result['dropped'], {'concepts': 0, 'mappings': 0}) + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=1, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=10) + def test_unnamed_mapping_naming_its_from_code_keeps_it(self): + concepts = [self.concept(code) for code in 'ABC'] + pairs = (('A', 'B'), ('B', 'C'), ('A', 'C')) + self.run_import([*concepts, *(self.mapping(f'M{index}', *pair) for index, pair in enumerate(pairs)), + self.version('v1')]) + lines = [] + for from_concept, to_concept in pairs: + line = self.unnamed_mapping(from_concept, to_concept) + line.pop('to_concept_url') + lines.append({**line, 'from_concept_code': from_concept, 'to_concept_code': to_concept}) + + importer = self.run_import([*concepts, *lines, self.version('v2')]) + + self.assertEqual(importer.json_result['dropped'], {'concepts': 0, 'mappings': 0}) + self.assertEqual(Mapping.objects.filter(parent__mnemonic='LOINC', id=F('versioned_object_id')).count(), 3) + + def test_seeding_needs_update_if_exists(self): + self.run_import([self.concept('A'), self.version('v1')]) + content = '\n'.join(json.dumps(line) for line in [self.source_line, self.concept('A'), self.version('v2')]) + + with self.assertRaises(DjangoValidationError) as ex: + BulkImportInline(content, 'ocladmin', False, isolated_version=True) + + self.assertEqual(ex.exception.message_dict, {'__all__': [SEED_FROM_IMPORT_NEEDS_UPDATE]}) + + @override_settings(SEED_FROM_IMPORT_LARGE_DROP_MIN=1, SEED_FROM_IMPORT_LARGE_DROP_PERCENT=10) + def test_unnamed_mappings_choose_in_file_order(self): + concepts = [self.concept(code) for code in 'ABC'] + pairs = (('A', 'B'), ('B', 'C')) + self.run_import([*concepts, *( + line for index, pair in enumerate(pairs) for line in ( + self.mapping(f'O{index}', *pair), {**self.mapping(f'N{index}', *pair), 'retired': True})), + self.version('v1')]) + retired_lines = [{**self.unnamed_mapping(*pair), 'retired': True} for pair in pairs for _ in range(2)] + + importer = self.run_import([*concepts, *retired_lines, self.version('v2')]) + + self.assertEqual(len(importer.failed), 0) + self.assertEqual(importer.json_result['dropped'], {'concepts': 0, 'mappings': 0}) + + def test_largest_dropped_id_counts_even_past_integer_range(self): + self.run_import([self.concept('A'), self.concept('B'), self.mapping('1', 'A', 'B'), + self.mapping('3000000000', 'B', 'A'), self.version('v1')]) + self.run_import([self.concept('A'), self.concept('B'), self.mapping('1', 'A', 'B'), self.version('v2')]) + + self.assertEqual(Source.objects.get(mnemonic='LOINC', version='HEAD').get_max_mapping_mnemonic(), 3000000000) + + def test_older_concept_version_indexes_its_releases_mappings(self): + self.run_import([self.concept('A'), self.concept('B'), self.version('v1')]) + self.run_import([self.concept('A', names=[{'name': 'A edited', 'locale': 'en', 'locale_preferred': True}]), + self.concept('B'), self.mapping('M', 'A', 'B'), self.version('v2')]) + v1_row = Source.objects.get(mnemonic='LOINC', version='v1').concepts.get(mnemonic='A') + self.assertFalse(v1_row.is_latest_version) + self.assertFalse(v1_row.get_indexed_mappings().exists()) + + self.run_import([self.concept('A', names=[{'name': 'A edited', 'locale': 'en', 'locale_preferred': True}]), + self.concept('B'), self.version('v3')]) + + self.assertFalse(v1_row.get_indexed_mappings().exists()) + v2_row = Source.objects.get(mnemonic='LOINC', version='v2').concepts.get(mnemonic='A') + self.assertEqual(list(v2_row.get_indexed_mappings().values_list('mnemonic', flat=True)), + [] if v2_row.is_latest_version else ['M']) + def test_new_ids_skip_those_of_dropped_codes(self): self.run_import([self.concept('A'), self.concept('B'), self.mapping('1', 'A', 'B'), self.mapping('2', 'B', 'A'), self.version('v1')]) @@ -7360,9 +7424,41 @@ def get_mapping_ids(url): '/orgs/Regen/sources/LOINC/v1/concepts/A/?includeMappings=true', HTTP_AUTHORIZATION='Token ' + self.token) self.assertEqual([item['id'] for item in response.data['mappings']], ['M1']) + response = self.client.get( + '/orgs/Regen/sources/LOINC/v1/concepts/A/?includeMappings=true&mappingBrief=true', + HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual( + [item['url'] for item in response.data['mappings']], ['/orgs/Regen/sources/LOINC/mappings/M1/']) + response = self.client.get( + '/orgs/Regen/sources/LOINC/v1/concepts/?includeMappings=true', HTTP_AUTHORIZATION='Token ' + self.token) + self.assertEqual({item['id']: [mapping['id'] for mapping in item['mappings']] for item in response.data}, + {'A': ['M1'], 'B': []}) + Source.objects.get(mnemonic='LOINC', version='v1').mappings.update(is_active=False) # an admin soft-delete self.assertEqual(get_mapping_ids('/orgs/Regen/sources/LOINC/v1/concepts/A/mappings/'), []) + def test_latest_that_is_head_embeds_each_mapping_once(self): + concept = IsolatedVersionImportTest.concept + BulkImportInline('\n'.join(json.dumps(line) for line in [ + {'type': 'Source', 'id': 'LOINC', 'name': 'LOINC', 'owner_type': 'Organization', 'owner': 'Regen', + 'default_locale': 'en', 'supported_locales': 'en'}, concept('A'), concept('B'), + IsolatedVersionImportTest.mapping('M1', 'A', 'B')]), 'ocladmin', True).run() + Source.objects.filter(mnemonic='LOINC', version='HEAD').update(released=True) + + response = self.client.get( + '/orgs/Regen/sources/LOINC/latest/concepts/A/?includeMappings=true', + HTTP_AUTHORIZATION='Token ' + self.token) + + self.assertEqual(response.status_code, 200) + self.assertEqual([item['id'] for item in response.data['mappings']], ['M1']) + + def test_seed_from_import_refuses_create_only(self): + response = self.client.post( + '/importers/bulk-import/?seed_from_import=true&update_if_exists=false', {'data': '{"type": "Concept"}'}, + HTTP_AUTHORIZATION='Token ' + self.token, format='json') + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data, {'exception': SEED_FROM_IMPORT_NEEDS_UPDATE}) + @patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) @patch('core.sources.models.index_source_concepts', Mock(__name__='index_source_concepts')) diff --git a/core/importers/views.py b/core/importers/views.py index bbcc8b629..2ff7d879f 100644 --- a/core/importers/views.py +++ b/core/importers/views.py @@ -29,6 +29,7 @@ get_export_service from core.importers.constants import ALREADY_QUEUED, INVALID_UPDATE_IF_EXISTS, NO_CONTENT_TO_IMPORT, INVALID_INDEX, \ INVALID_SEED_FROM_IMPORT, SEED_FROM_IMPORT_IMPORT_TYPE, SEED_FROM_IMPORT_ENDPOINT +from core.sources.constants import SEED_FROM_IMPORT_NEEDS_UPDATE from core.importers.importer import Importer, ResourceImporter from core.importers.input_parsers import ImportContentParser from core.importers.limits import ( @@ -65,6 +66,8 @@ def get_seed_from_import_param(request, supported=True): return None, Response({'exception': INVALID_SEED_FROM_IMPORT}, status=status.HTTP_400_BAD_REQUEST) if seed_from_import == 'true' and not supported: return None, Response({'exception': SEED_FROM_IMPORT_ENDPOINT}, status=status.HTTP_400_BAD_REQUEST) + if seed_from_import == 'true' and request.GET.get('update_if_exists', 'true') == 'false': + return None, Response({'exception': SEED_FROM_IMPORT_NEEDS_UPDATE}, status=status.HTTP_400_BAD_REQUEST) return seed_from_import == 'true', None diff --git a/core/integration_tests/tests_concepts.py b/core/integration_tests/tests_concepts.py index 9b4597af6..1e4f55d78 100644 --- a/core/integration_tests/tests_concepts.py +++ b/core/integration_tests/tests_concepts.py @@ -4840,6 +4840,8 @@ def test_source_version_list(self): organization=self.source.organization, mnemonic=self.source.mnemonic, version='v1') for concept in self.concepts: version.concepts.add(concept.get_latest_version()) + for mapping in Mapping.objects.filter(parent=self.source, is_latest_version=True): + version.mappings.add(mapping) # a version's concepts embed its own mappings self.assert_same_with_and_without_batching(version.uri + 'concepts/') self.assertTrue(any(self.mappings_by_concept(version.uri + 'concepts/').values())) diff --git a/core/mappings/serializers.py b/core/mappings/serializers.py index 35dd4767f..0f6545851 100644 --- a/core/mappings/serializers.py +++ b/core/mappings/serializers.py @@ -203,6 +203,11 @@ def get_cascade_target_concept_name(obj): return obj.to_concept_name or get(obj, 'to_concept.display_name') + +class EmbeddedMappingMinimalSerializer(MappingMinimalSerializer): + """A release's mapping embedded in its concept: url names the mapping, as the full form's does, not the revision.""" + url = CharField(source='versioned_object_url', read_only=True) + class MappingReverseMinimalSerializer(ModelSerializer): id = CharField(source='mnemonic', read_only=True) type = CharField(source='resource_type', read_only=True) diff --git a/core/sources/constants.py b/core/sources/constants.py index d6c87ea7b..2d69da9cb 100644 --- a/core/sources/constants.py +++ b/core/sources/constants.py @@ -28,6 +28,7 @@ ALLOW_LARGE_DROP = 'allow_large_drop' ISOLATED_VERSION_META_INVALID = 'meta must be an object, and meta.display.concept_filter_order a list of codes.' ISOLATED_VERSION_LIST_FIELD_INVALID = '{field} must be a list.' +SEED_FROM_IMPORT_NEEDS_UPDATE = 'A seed_from_import import updates what it resends, so update_if_exists must be true.' ISOLATED_VERSION_DELETE_LINE = \ 'A seed_from_import import cannot delete codes. Leave a code out of the file to drop it from HEAD.' ISOLATED_METADATA_FIELDS = ( diff --git a/core/sources/models.py b/core/sources/models.py index ff3624c89..911315946 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -1036,9 +1036,9 @@ def get_max_mapping_mnemonic(self): def get_max_mnemonic_for_resource(queryset): return get( queryset.filter( - mnemonic__regex=r'^\d+$' + mnemonic__regex=r'^\d{1,18}$' # fits a bigint, so one oversized id can't fail the whole query ).annotate( - mnemonic_int=Cast('mnemonic', models.IntegerField()) + mnemonic_int=Cast('mnemonic', models.BigIntegerField()) ).aggregate( max_val=Max('mnemonic_int')), 'max_val', None ) From a59f88f698d7438bddb4e2795fa3abfd0920ed05 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 21:17:21 -0500 Subject: [PATCH 8/8] Final review fixes for #985: FE.2 and match_algorithms off HEAD (#1014) * OpenConceptLab/ocl_online#655 | A mapping line whose from URL doesn't resolve matches a mapping by code only within that URL's source, so an import never updates or retires another source's mapping (FE.2) MappingImporter.get_queryset and the seeding preflight's MappingMatcher now also require the mapping's from_source_url to be the line's from source when the from concept URL doesn't resolve, with or without from_concept_code. The same source's mapping still matches, so re-importing an id-less line that names its from code updates it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qWhAoApU55xQW8puav * OpenConceptLab/ocl_online#655 | A seeding import's Source Version line sets match_algorithms on the new version only; HEAD keeps its own and its vectors aren't resynced apply_version_metadata_to_head skips match_algorithms, which stays in ISOLATED_METADATA_FIELDS so the line still sets and checks it on the version, as POST .../versions/ leaves HEAD's alone. Nothing else it copies can change HEAD's semantic flag, so the HEAD vector sync that went with it is dropped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qWhAoApU55xQW8puav * OpenConceptLab/ocl_online#655 | An unresolved from URL's source is matched as mappings are saved: by link to the source it resolves to, else by the stored URL (FE.2 review, pass 1) A mapping saved from a canonical from URL is linked to the source the URL resolves to and stores that source's own URL, so a text match on the line's URL missed it: a re-import failed uniqueness and a DELETE found nothing. A linked mapping now matches when it's linked to the source the line's URL resolves to, and an unlinked one when its stored from source URL is the line's, in MappingImporter and MappingMatcher alike. That also stops a stale stored URL from matching a mapping linked to another source. Each update variant in the cross-source test now starts from S1's mapping alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qWhAoApU55xQW8puav * OpenConceptLab/ocl_online#655 | The from source lookup moves into its criteria helper, inside pylint's local-variable limit for MappingImporter.get_queryset Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qWhAoApU55xQW8puav * OpenConceptLab/ocl_online#655 | An unresolved from URL's source is compared by identity when both sides have one, else by the URLs a mapping stores for it (FE.2 review, pass 2) The line's from source URL is resolved versionless, so an explicit HEAD path names its source. A mapping's source is its from source link, else its from concept's source; when the line's URL resolves to a source and the mapping has one, the two must be the same. Otherwise the mapping's stored from source URL must be one the URL is stored as, which includes the resolution URL a version-qualified canonical URL is stored under. A mapping linked to a source since retired is found again by its URL, as before this PR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qWhAoApU55xQW8puav * OpenConceptLab/ocl_online#655 | Revert the pass 2 change to from source matching: its versionless lookup misreads some canonical URLs and its URL fallback matches mappings linked elsewhere This reverts commit 42aa7a40, which answered pass 2's three P2 findings. The final Codex check found it broke more than it fixed: stripping a version segment can resolve a canonical URL to another source, and the fallback for a URL that resolves to no source matched mappings linked to another source. The tree returns to 1fdb8274, which pass 2 found free of P0 and P1 defects; F2.1 to F2.3 are accepted as P2 edge cases. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qWhAoApU55xQW8puav --------- Co-authored-by: Claude Opus 5.5 --- core/importers/models.py | 60 +++++++++++--- core/importers/tests.py | 169 +++++++++++++++++++++++++++++++++++---- core/sources/models.py | 7 +- 3 files changed, 204 insertions(+), 32 deletions(-) diff --git a/core/importers/models.py b/core/importers/models.py index 23c5dd09c..631b59293 100644 --- a/core/importers/models.py +++ b/core/importers/models.py @@ -9,7 +9,7 @@ from django.conf import settings from django.core.exceptions import ValidationError from django.db import transaction -from django.db.models import F +from django.db.models import F, Q from ocldev.oclfleximporter import OclFlexImporter from pydash import compact, get @@ -427,12 +427,12 @@ def set_head_defaults(self, source): class MappingMatcher: """ Which of HEAD's mappings an import's lines would update, found as MappingImporter finds them: by id, else by map - type, the from concept or code, and the target concept, code or source the line names. Of several matches, the - importer updates the first one not retired, else the newest, with the lines before it already applied. + type, the from concept or its source and code, and the target concept, code or source the line names. Of several + matches, the importer updates the first one not retired, else the newest, with the lines before it already applied. """ FIELDS = ('id', 'mnemonic', 'retired', 'is_active', 'map_type', 'from_concept__versioned_object_id', - 'from_concept_code', 'to_concept__versioned_object_id', 'to_concept_code', 'to_source_url', - 'to_source__uri') + 'from_concept_code', 'from_source_id', 'from_source_url', 'to_concept__versioned_object_id', + 'to_concept_code', 'to_source_url', 'to_source__uri') def __init__(self, head): self.rows, self.by_mnemonic, self.by_from_id, self.by_from_code = {}, {}, {}, {} @@ -466,12 +466,15 @@ def kept(self, lines): source_uris = {to_parent_uri(drop_version(line['to_concept_url'])) for line in unnamed if line.get('to_concept_url') and not line.get('to_source_url')} existing_sources = set(Source.objects.filter(uri__in=source_uris).values_list('uri', flat=True)) + from_source_ids = {url: MappingImporter.get_source_id_by_url(url) for url in { + to_parent_uri(drop_version(line['from_concept_url'])) for line in unnamed + if line.get('from_concept_url') and drop_version(line['from_concept_url']) not in resolved}} kept = set() for line in lines: if line.get('id') not in (None, ''): row_id = self.by_mnemonic.get(str(line['id'])) else: - row_id = self.choose(self.get_candidates(line, resolved, existing_sources)) + row_id = self.choose(self.get_candidates(line, resolved, existing_sources, from_source_ids)) if row_id: # a seeding import leaves a field it doesn't send at its default, so the next line sees this self.rows[row_id]['retired'] = line.get('retired') in (True, 'true', 'True') @@ -479,16 +482,26 @@ def kept(self, lines): kept.add(row_id) return kept - def get_candidates(self, line, resolved, existing_sources): # pylint: disable=too-many-locals + @staticmethod + def is_same_from_source(row, from_source_url, from_source_id): + """MappingImporter.get_same_from_source_criteria, for one row.""" + if row['from_source_id']: + return row['from_source_id'] == from_source_id + return row['from_source_url'] == drop_version(from_source_url) + + def get_candidates(self, line, resolved, existing_sources, from_source_ids): # pylint: disable=too-many-locals map_type, from_code = line.get('map_type'), line.get('from_concept_code') from_url = drop_version(line.get('from_concept_url') or '') from_id = resolved.get(from_url) + checks = [] if from_id: candidates = self.by_from_id.get((map_type, from_id), []) else: codes = self.variations(from_code) if from_code else {self.last_segment(from_url)} if from_url else set() candidates = [row_id for code in codes for row_id in self.by_from_code.get((map_type, code), [])] - checks = [] + from_source_url = to_parent_uri(from_url) + checks.append(lambda row: self.is_same_from_source( + row, from_source_url, from_source_ids.get(from_source_url))) if from_code and from_id: checks.append(lambda row: row['from_concept_code'] in self.variations(from_code)) to_url, to_code, to_source_url = drop_version(line.get('to_concept_url') or ''), line.get( @@ -920,10 +933,14 @@ def get_queryset(self): # pylint: disable=too-many-branches versionless_from_concept_url = drop_version(from_concept_url) from_concept_id = self.get_cached_versioned_concept_id_by_uri(versionless_from_concept_url) + same_from_source = Q() if from_concept_id is not None: filters['from_concept__versioned_object_id'] = from_concept_id - elif not from_concept_code: - filters['from_concept_code'] = compact(versionless_from_concept_url.split('/'))[-1] + else: + # a code the URL doesn't resolve matches only within the URL's source, never another source's mapping + same_from_source = self.get_same_from_source_criteria(to_parent_uri(versionless_from_concept_url)) + if not from_concept_code: + filters['from_concept_code'] = compact(versionless_from_concept_url.split('/'))[-1] if to_concept_url: versionless_to_concept_url = drop_version(to_concept_url) to_concept_id = self.get_cached_versioned_concept_id_by_uri(versionless_to_concept_url) @@ -944,10 +961,31 @@ def get_queryset(self): # pylint: disable=too-many-branches filters['to_concept_code__in'] = [ *Concept.get_encoded_str_variations(to_concept_code), to_concept_code.replace(' ', '+')] - self.queryset = Mapping.objects.filter(**filters) + self.queryset = Mapping.objects.filter(same_from_source, **filters) return self.queryset + @staticmethod + def get_source_id_by_url(url): + """The source a mapping saved with this from source URL is linked to: the one it resolves to, as on save.""" + source, _ = Source.resolve_reference_expression(url, None, HEAD) + return source.id if isinstance(source, Source) else None + + def get_cached_source_id_by_url(self, url): + cache = self.cache.setdefault('source_id_by_url', {}) + if url not in cache: + cache[url] = self.get_source_id_by_url(url) + return cache[url] + + def get_same_from_source_criteria(self, from_source_url): + """ + A mapping from the source a from source URL names: one linked to a source, if that's the source the URL + resolves to, and one that isn't, if it was saved with that URL. MappingMatcher.is_same_from_source alike. + """ + from_source_id = self.get_cached_source_id_by_url(from_source_url) + criteria = Q(from_source__isnull=True, from_source_url=drop_version(from_source_url)) + return criteria | Q(from_source_id=from_source_id) if from_source_id else criteria + def parse(self): source = self.get_cached_parent_source() self.data = self.get_filter_allowed_fields() diff --git a/core/importers/tests.py b/core/importers/tests.py index 42874f209..9943f8722 100644 --- a/core/importers/tests.py +++ b/core/importers/tests.py @@ -42,7 +42,7 @@ CREATED, UPDATED, DELETED, PERMISSION_DENIED, UNCHANGED, FAILED, NOT_FOUND, \ BaseImporter, BaseResourceImporter, OrganizationImporter, SourceImporter, SourceVersionImporter, \ CollectionImporter, CollectionVersionImporter, ConceptImporter, MappingImporter, ReferenceImporter, ImportIndexer, \ - IsolatedVersionCommit + IsolatedVersionCommit, MappingMatcher from core.importers.views import csv_file_data_to_input_list, ImportRetrieveDestroyMixin from core.mappings.documents import MappingDocument from core.mappings.models import Mapping @@ -1417,6 +1417,145 @@ def test_mapping_import_with_id_moved_to_another_from_concept_refreshes_the_prev old_from.versioned_object_id, new_from.versioned_object_id}, {old_from.versioned_object_id, new_from.versioned_object_id}) + @staticmethod + def cross_source_mapping(org_mnemonic): + """ + A mapping in Maps from X in S1 to T/Y, where S1 has no concept X, so a line's from URL doesn't resolve. S2 + exists and has no X either, and S3 doesn't exist. + """ + org = OrganizationFactory(mnemonic=org_mnemonic) + maps = OrganizationSourceFactory(organization=org, mnemonic='Maps') + OrganizationSourceFactory(organization=org, mnemonic='S1') + OrganizationSourceFactory(organization=org, mnemonic='S2') + ConceptFactory(parent=OrganizationSourceFactory(organization=org, mnemonic='T'), mnemonic='Y') + + def line(from_source, **extra): + return { + 'type': 'Mapping', 'map_type': 'Same As', 'owner_type': 'Organization', 'owner': org.mnemonic, + 'source': maps.mnemonic, 'from_concept_url': f'{org.uri}sources/{from_source}/concepts/X/', + 'to_concept_url': f'{org.uri}sources/T/concepts/Y/', **extra + } + + BulkImportInline(content=None, username='ocladmin', update_if_exists=True, input_list=[line('S1')]).run() + return Mapping.objects.get(parent=maps, id=F('versioned_object_id')), line + + @staticmethod + def import_paths(): + """An ordinary inline import's report, and that of one part of a parallel import, as its worker runs it.""" + def inline(lines): + return BulkImportInline( + content=None, username='ocladmin', update_if_exists=True, input_list=lines).run()['report'] + + def parallel_part(lines): + return bulk_import_parts_inline(lines, 'ocladmin', True)['report'] # pylint: disable=no-value-for-parameter + + return {'inline': inline, 'parallel': parallel_part} + + @staticmethod + def register_canonical_url(source, canonical_url): + Toggle.objects.filter(name=URL_REGISTRY_IN_RESOLVE_REFERENCE_TOGGLE).update( + dev=True, qa=True, demo=True, staging=True, who_staging=True, production=True) + Source.objects.filter(id=source.id).update(canonical_url=canonical_url) + GlobalURLRegistryFactory(url=canonical_url, namespace=source.organization.uri) + return canonical_url + + @patch('core.importers.models.batch_index_resources', Mock()) + def test_mapping_line_without_id_never_updates_another_sources_mapping_by_code(self): + for path, run in self.import_paths().items(): + for from_source in ('S2', 'S3'): + for extra in ({}, {'from_concept_code': 'X'}): + with self.subTest(path, from_source=from_source, **extra): + mapping, line = self.cross_source_mapping(f'CrossUpdate{path}{from_source}{len(extra)}') + versions = Mapping.objects.filter(versioned_object_id=mapping.id).count() + + report = run([line(from_source, extras={'edited': True}, **extra)]) + + self.assertEqual((report['created'], report['updated'], report['failed']), (1, 0, 0)) + mapping.refresh_from_db() + self.assertEqual((mapping.from_source_url, mapping.extras), + (mapping.parent.organization.uri + 'sources/S1/', {})) + self.assertEqual(Mapping.objects.filter(versioned_object_id=mapping.id).count(), versions) + + @patch('core.importers.models.batch_index_resources', Mock()) + def test_mapping_delete_line_without_id_never_retires_another_sources_mapping_by_code(self): + for path, run in self.import_paths().items(): + with self.subTest(path): + mapping, line = self.cross_source_mapping(f'CrossDelete{path}') + + reports = [run([{**line(from_source, **extra), '__action': 'DELETE'}]) + for from_source in ('S2', 'S3') for extra in ({}, {'from_concept_code': 'X'})] + + self.assertEqual([(report['deleted'], report['not_found']) for report in reports], [(0, 1)] * 4) + mapping.refresh_from_db() + self.assertFalse(mapping.retired) + + @patch('core.importers.models.batch_index_resources', Mock()) + def test_mapping_line_without_id_still_matches_its_own_sources_mapping_by_code(self): + for path, run in self.import_paths().items(): + with self.subTest(path): + mapping, line = self.cross_source_mapping(f'CrossSame{path}') + + reports = [run([line('S1', extras={'edit': 1})]), + run([line('S1', extras={'edit': 2}, from_concept_code='X')]), + run([{**line('S1', from_concept_code='X'), '__action': 'DELETE'}])] + + self.assertEqual([(report['updated'], report['deleted']) for report in reports], + [(1, 0), (1, 0), (0, 1)]) + mapping.refresh_from_db() + self.assertEqual((mapping.extras, mapping.retired), ({'edit': 2}, True)) + + @patch('core.importers.models.batch_index_resources', Mock()) + def test_mapping_line_without_id_through_a_canonical_url_matches_the_source_it_resolves_to(self): + """The mapping is saved linked to S1 under S1's own URL, so a line naming S1's canonical URL still finds it.""" + for path, run in self.import_paths().items(): + with self.subTest(path): + mapping, line = self.cross_source_mapping(f'CrossCanonical{path}') + canonical_url = self.register_canonical_url( + Source.objects.get(organization=mapping.parent.organization, mnemonic='S1', version='HEAD'), + f'https://s1-{path}.example.test/') + canonical_line = {**line('S1'), 'from_concept_url': canonical_url + 'concepts/X/'} + + self.assertEqual(MappingMatcher(mapping.parent).kept([canonical_line]), {mapping.id}) + reports = [run([{**canonical_line, 'extras': {'edit': 1}}]), + run([{**canonical_line, 'extras': {'edit': 2}, 'from_concept_code': 'X'}]), + run([{**canonical_line, '__action': 'DELETE'}])] + + self.assertEqual([(report['updated'], report['deleted'], report['failed']) for report in reports], + [(1, 0, 0), (1, 0, 0), (0, 1, 0)]) + mapping.refresh_from_db() + self.assertEqual((mapping.extras, mapping.retired), ({'edit': 2}, True)) + + @patch('core.importers.models.batch_index_resources', Mock()) + def test_mapping_delete_line_without_id_never_retires_a_mapping_linked_to_another_source(self): + """A mapping linked to S1 that still has a URL now registered to S2 isn't S2's to retire.""" + for path, run in self.import_paths().items(): + with self.subTest(path): + mapping, line = self.cross_source_mapping(f'CrossLinked{path}') + canonical_url = self.register_canonical_url( + Source.objects.get(organization=mapping.parent.organization, mnemonic='S2', version='HEAD'), + f'https://s2-{path}.example.test/') + Mapping.objects.filter(versioned_object_id=mapping.id).update(from_source_url=canonical_url) + stale_line = {**line('S1'), 'from_concept_url': canonical_url + 'concepts/X/'} + + self.assertEqual(MappingMatcher(mapping.parent).kept([stale_line]), set()) + report = run([{**stale_line, '__action': 'DELETE'}]) + + self.assertEqual((report['deleted'], report['not_found']), (0, 1)) + mapping.refresh_from_db() + self.assertFalse(mapping.retired) + + @patch('core.importers.models.batch_index_resources', Mock()) + def test_seeding_preflight_matches_a_code_only_within_the_from_urls_source(self): + mapping, line = self.cross_source_mapping('CrossMatcher') + + for lines, kept in ( + ([line(source, **extra) for source in ('S2', 'S3') for extra in ({}, {'from_concept_code': 'X'})], + set()), + ([line('S1')], {mapping.id}), + ([line('S1', from_concept_code='X')], {mapping.id}), + ): + self.assertEqual(MappingMatcher(mapping.parent).kept(lines), kept) + def cloned_mapping_in_local_source(self): """A mapping cloned into a local source before clones fixed source URLs: linked to local concepts, with its target URL still on the origin.""" @@ -6901,14 +7040,21 @@ def test_version_line_metadata_is_validated_before_content(self): self.assertIn('filters', importer.failed[0]['errors']) self.assertFalse(Source.objects.filter(mnemonic='LOINC', version='v2').exists()) - def test_seeding_line_match_algorithms_reach_head(self): + @patch('core.sources.models.Source.sync_concept_vectors_async', autospec=True) + def test_seeding_line_match_algorithms_stay_off_head(self, sync_mock): self.run_import([self.concept('A'), self.version('v1')]) - Source.objects.filter(mnemonic='LOINC', version='HEAD').update(match_algorithms=['es', 'llm']) - self.run_import([self.concept('A'), self.version('v2', match_algorithms=['es'])]) + for version, head_algorithms, line_algorithms in (('v2', ['es'], ['es', 'llm']), ('v3', ['es', 'llm'], ['es'])): + Source.objects.filter(mnemonic='LOINC', version='HEAD').update(match_algorithms=head_algorithms) - self.assertEqual(Source.objects.get(mnemonic='LOINC', version='HEAD').match_algorithms, ['es']) - self.assertEqual(Source.objects.get(mnemonic='LOINC', version='v2').match_algorithms, ['es']) + self.run_import([self.concept('A'), self.version(version, match_algorithms=line_algorithms)]) + + self.assertEqual( + sorted(Source.objects.get(mnemonic='LOINC', version='HEAD').match_algorithms), head_algorithms) + self.assertEqual( + sorted(Source.objects.get(mnemonic='LOINC', version=version).match_algorithms), line_algorithms) + # the semantic version syncs its own vectors; HEAD's aren't touched + self.assertNotIn('HEAD', [call_args.args[0].version for call_args in sync_mock.call_args_list]) def test_plural_user_owner_type_is_read_as_the_importers_read_it(self): users_line = {'owner_type': 'users', 'owner': 'Regen', 'source': 'LOINC'} @@ -7111,17 +7257,6 @@ def test_dropped_codes_leave_heads_queries_and_bump_its_last_update(self): self.assertFalse(head.get_mappings_queryset().exists()) self.assertGreater(head.last_child_update, last_update) - @patch('core.sources.models.Source.sync_concept_vectors_async') - def test_semantic_change_on_head_syncs_its_vectors(self, sync_mock): - self.run_import([self.concept('A'), self.version('v1')]) - Source.objects.filter(mnemonic='LOINC', version='HEAD').update(match_algorithms=['es', 'llm']) - - self.run_import([self.concept('A'), self.version('v2', match_algorithms=['es'])]) - sync_mock.assert_called_once() - sync_mock.reset_mock() - self.run_import([self.concept('A'), self.version('v3', match_algorithms=['es'])]) - sync_mock.assert_not_called() - def test_hierarchy_repair_links_a_child_version_url(self): from core.common.tasks import make_hierarchy self.run_import([self.concept('P'), self.concept('C'), self.version('v1')]) diff --git a/core/sources/models.py b/core/sources/models.py index 911315946..8ad1d800d 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -258,8 +258,9 @@ def apply_version_metadata_to_head(self, head): self.seeded_from = {'type': SEEDED_FROM_REPO_VERSION, 'url': head.get_version_url(HEAD)} return head.seeded_from = {'type': SEEDED_FROM_REPO_VERSION, 'url': head.get_version_url(self.version)} - was_semantic = bool(head.has_semantic_match_algorithm) - fields = [field for field in get(self, '_metadata_fields') or [] if field in ISOLATED_METADATA_FIELDS] + # HEAD keeps its own match algorithms, as after POST .../versions/: the line sets them on the version only + fields = [field for field in get(self, '_metadata_fields') or [] if field in ISOLATED_METADATA_FIELDS and + field != 'match_algorithms'] for field in fields: setattr(head, field, getattr(self, field)) for field in ISOLATED_REQUIRED_METADATA_FIELDS: @@ -271,8 +272,6 @@ def apply_version_metadata_to_head(self, head): **(self.extras or {}) } head.save() - if bool(head.has_semantic_match_algorithm) != was_semantic: # as an edit of HEAD does - transaction.on_commit(lambda: head.sync_concept_vectors_async(self.created_by), robust=True) def queue_index_dropped_children(self, concept_ids, mapping_ids): """