Skip to content
148 changes: 146 additions & 2 deletions core/collections/evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@

from core.collections.constants import EXPANSION_FHIR_RULES_TOGGLE
from core.common.models import ReferenceResolution
from core.common.utils import is_canonical_uri, decode_string, drop_version
from core.common.utils import is_canonical_uri, decode_string, drop_version, split_canonical
from core.side_effects import refusing_side_effects, refuse, DeadlineExceeded, current_deadline
from core.toggles.models import Toggle
from core.url_registry.constants import URL_REGISTRY_IN_RESOLVE_REFERENCE_TOGGLE


class EvaluationTooCostly(Exception):
Expand Down Expand Up @@ -106,6 +107,10 @@ class ExpansionEvaluation:
codes: None, or the codes every reference evaluated under it is narrowed to, while narrowed_to() sets them. They're
compared with concepts' codes as OCL stores them (a reference's own code decoded), so a caller with a code spelled
otherwise gives each form OCL may store it in (FHIR's: core.fhir.ops.concepts.stored_codes).

supplements: the code system supplements its request names (url or url|version). Under FHIR's rules they apply,
with those a collection version declares and those it applies by default (supplements_for,
core.sources.supplements).
"""
is_request_time = False
deadline = None # time.monotonic() by which a request-time evaluation ends
Expand All @@ -114,11 +119,17 @@ class ExpansionEvaluation:
answers_caller = False # while open at request time for its caller (at_request_time's for_caller)
# the collection versions being evaluated under it, outermost first, as one's imports are (core.collections.imports)
import_chain = ()
has_default_supplements = False # whether it may apply supplements nobody names or declares (default_supplements)

def __init__(self, fhir_rules=None, resolution=None, caller=None):
def __init__(self, fhir_rules=None, resolution=None, caller=None, supplements=()):
self._fhir_rules = fhir_rules
self.resolution = resolution
self.caller = caller if getattr(caller, 'is_authenticated', False) else None
self.named_supplements = tuple(supplements or ())
# (code system version id, collection version id): (the supplements applied, the entries named or declared that
# applied)
self.supplement_uses = {}
self.found_supplements = {} # (entry named or declared, viewer id): the supplement version it names, or None
self.own_expansion_ids = set() # those built under it at request time (Expansion.build_at_request_time)
self.viewable = {} # (version class, version id, viewer id): what can_view answered while it's open
# expansion id: (the version parameters, the codes it's narrowed to) it was built under at request time under it
Expand Down Expand Up @@ -174,6 +185,7 @@ def at_request_time(self, seconds=None, for_caller=True):
connection.execute_wrapper(self.within_deadline), refusing_on_commit():
connection.evaluation_statement_timeout = None # none set by an evaluation in this block yet
self.viewable = {} # read again for each request: access can change between them
self.supplement_uses, self.found_supplements = {}, {} # and so the supplements it applies
near_limit = sorted(
table for table, used in link_sequence_usage().items()
if used is None or used >= LINK_SEQUENCE_LIMIT)
Expand Down Expand Up @@ -331,6 +343,138 @@ def resolve(self, klass, url, namespace=None, version=None):
return klass.resolve_reference_expression(
url, namespace, version, resolution=self.resolution or EvaluationResolution(self))

# --- code system supplements (core.sources.supplements) ---
def asks_supplements(self, collection_version=None):
"""Whether any supplement may apply under it: its request names one, the collection version declares one, or
it applies some by default. Read before its rules, so an evaluation that meets none never reads OCL's toggle"""
return bool(self.named_supplements or getattr(collection_version, 'declared_supplements', None) or
self.has_default_supplements)

def supplements_for(self, base, collection_version=None):
"""
The supplements (SupplementUse) that apply to a code system version under FHIR's rules, when it's evaluated or
answered for `collection_version` (or for none): those its request names, then those the collection version
declares, then those it applies by default (default_supplements), each only where it applies to that version
(applies_to, D2). One version a supplement: the version named or declared, else the newest that applies.
One that can't be found, or that the caller can't see, is left out (D9): require_applied says which named or
declared ones are missing. None apply under OCL's own rules, nor to a supplement.
"""
if not getattr(base, 'id', None) or base.is_supplement or not self.asks_supplements(collection_version) or \
not self.fhir_rules:
return []
key = (base.id, getattr(collection_version, 'id', None))
if key not in self.supplement_uses:
self.supplement_uses[key] = self.choose_supplements(base, collection_version)
return self.supplement_uses[key][0]

def choose_supplements(self, base, collection_version):
"""supplements_for's choice, worked out: (the SupplementUses, the entries named or declared that applied)"""
from core.sources import supplements
chosen, applied = {}, set() # a supplement's identity: (its use, whether the entry named its version)
declared = getattr(collection_version, 'declared_supplements', None) or ()
for how, entries, namespace in (
(supplements.NAMED, self.named_supplements, None),
(supplements.DECLARED, declared, self.declaring_namespace(collection_version) if declared else None)):
for entry in entries:
found = self.supplement_named(entry, base, collection_version, namespace)
if found is None:
continue
applied.add(entry)
key, pinned = supplements.identity_of(found), supplements.pins_a_version(entry)
if key not in chosen or (pinned and not chosen[key][1]):
chosen[key] = (supplements.SupplementUse(found, how), pinned)
for found in self.default_supplements(base):
key = supplements.identity_of(found)
if key not in chosen and supplements.applies_to(found, base) and self.can_view_supplement(
found, collection_version):
chosen[key] = (supplements.SupplementUse(found, supplements.DEFAULT), False)
return [use for use, _ in chosen.values()], applied

def supplement_named(self, entry, base, collection_version=None, namespace=None):
"""The version of a supplement named or declared (url or url|version, resolved in `namespace`) that applies to
`base` and that its reader can see (can_view_supplement): the version named; else the one it resolves to, or
failing that its newest release that does. None when there's none: nothing found, not a supplement, or none
the reader can see that applies"""
from core.sources.supplements import applies_to, newest_applying
from core.sources.supplements import pins_a_version
url, version = split_canonical(entry)
key = (entry, namespace)
if key not in self.found_supplements:
found = self.resolve_supplement(url, version or None, namespace)
self.found_supplements[key] = found if getattr(found, 'id', None) and getattr(
found, 'is_supplement', False) else None
found = self.found_supplements[key]
if found is None:
return None

def visible(candidate):
return self.can_view_supplement(candidate, collection_version)
if visible(found) and applies_to(found, base):
return found
return None if pins_a_version(entry) else newest_applying(found, base, visible)

def resolve_supplement(self, url, version=None, namespace=None):
"""The source version a supplement's canonical (or OCL path) and version name, as references resolve them, in
`namespace`; one with no id when nothing's there. A subclass with content of its own looks there first"""
from core.sources.models import Source
from core.sources.supplements import stored_version
return self.resolve(Source, url, namespace, stored_version(version))[0]

@staticmethod
def declaring_namespace(collection_version):
"""Where a collection version's declared supplements resolve: its owner's namespace while the URL registries
are on, as its references' canonicals do (Expansion.get_system_version_namespace)"""
return collection_version.parent_url if Toggle.get(URL_REGISTRY_IN_RESOLVE_REFERENCE_TOGGLE) else None

def default_supplements(self, base): # pylint: disable=unused-argument
"""
The supplement versions it applies to a code system version though nobody names or declares them: none here. A
stored supplement isn't applied by default until OCL decides who sets a code system's default supplements
(OpenConceptLab/ocl_issues#3033 D3, D4); a subclass with content of its own gives the global supplements it
carries.
"""
return []

def can_view_supplement(self, version, collection_version=None):
"""Whether a supplement version may apply for whom it answers: at request time for its caller the caller; else
the creator of the collection version that declares it, as for its references, and with none the caller"""
if self.answers_caller or collection_version is None:
return self.can_view(version)
return version.can_view_all_content(collection_version.created_by)

def require_applied(self, bases, collection_version=None, named=True):
"""
Under FHIR's rules, SupplementNotFound for the first supplement named (unless `named` is False: for a value set
the one answered for imports, whose own declarations alone are its), then declared by `collection_version`,
that applies to none of these code system versions (those a request used): one that can't be found, one the
caller can't see, and one pinned to other versions all read the same (D9). What answers a request asks it;
building an expansion never does, so a stored build doesn't fail on it.
"""
from core.sources.supplements import SupplementNotFound
entries = [*(self.named_supplements if named else ()),
*(getattr(collection_version, 'declared_supplements', None) or ())]
if not entries or not self.fhir_rules:
return
applied = set()
for base in bases:
self.supplements_for(base, collection_version)
applied |= self.supplement_uses.get((base.id, getattr(collection_version, 'id', None)), ((), set()))[1]
missing = next((entry for entry in entries if entry not in applied), None)
if missing is not None:
raise SupplementNotFound(missing)

def merged(self, base, concepts, collection_version=None):
"""{concept id: MergedConcept} of a code system version's concepts with the supplements that apply to it
(supplements_for; core.sources.supplements.merge)"""
from core.sources.supplements import merge
return merge(concepts, self.supplements_for(base, collection_version), base.case_sensitive is not False,
codes_as_written=self.codes_as_written(base), supplement_as_written=self.codes_as_written)

def codes_as_written(self, version): # pylint: disable=unused-argument
"""Whether a source version's codes are as written (merge): not OCL's stored content, which may hold a code
percent-encoded; a subclass's own content may be"""
return False

@staticmethod
def split_version(url, version=None):
"""
Expand Down
15 changes: 13 additions & 2 deletions core/collections/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
(4) it read no other value set. An expansion records which value set versions it read, not what they held then, so
nothing about what it took from them, however deep (the versions they used, their loops), can be checked: such
an expansion is always evaluated again, from what those value sets hold now.
(5) no code system supplement applies, where it's evaluated now, to a source version it used
(ExpansionEvaluation.supplements_for: one the request names, one the version declares, or one applied by
default): a filter on a property a supplement declares reads its values (core.sources.supplements), which its
default expansion, built without them, didn't.
Otherwise the imported version's references are evaluated again, in an expansion that isn't kept
(Expansion.build_at_request_time). Within an evaluation open at request time that expansion lasts as long as the
evaluation; otherwise it's built in one opened for it, rolled back once its members are read (EvaluatedImport). What
Expand Down Expand Up @@ -358,11 +362,18 @@ def read_of(self, version):
return self.read.get((version.id, narrowing_of(self.evaluation)), self.read.get((version.id, None)))

def is_stable(self, version, stored):
"""Whether a version's default expansion may be read as it is: (1) to (4) in the module's list"""
"""Whether a version's default expansion may be read as it is: (1) to (5) in the module's list"""
return not stored.recorded_explicit_collection_versions and not stored.recorded_evaluated_collection_versions \
and (stored.versions_apart or self.uses_one_version_per_source(stored)) and \
not self.uses_own_url(version, stored) and \
self.versions_hold(version, stored) and not self.resolves_now(stored)
self.versions_hold(version, stored) and not self.resolves_now(stored) and \
not self.supplemented(version, stored)

def supplemented(self, version, stored):
"""(5): whether a supplement applies, where the version is evaluated now, to a source version its default
expansion used; nothing is read when none may (ExpansionEvaluation.asks_supplements)"""
return self.evaluation.asks_supplements(version) and any(
self.evaluation.supplements_for(base, version) for base in stored.recorded_source_versions)

@staticmethod
def uses_one_version_per_source(expansion):
Expand Down
Loading
Loading