Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
40b800a
OpenConceptLab/ocl_online#798 | A FHIR update saves onto HEAD from HE…
paynejd Dec 1, 2026
0262e74
OpenConceptLab/ocl_online#798 | A FHIR update keeps HEAD's validation…
paynejd Dec 1, 2026
81e6f57
OpenConceptLab/ocl_online#798 | Merge fhir-452-b9-codesystem (FHIR up…
paynejd Dec 1, 2026
2a33ebe
OpenConceptLab/ocl_online#798 | A FHIR update applies the resource to…
paynejd Dec 1, 2026
06fc615
OpenConceptLab/ocl_online#798 | A FHIR update's new version is HEAD a…
paynejd Dec 1, 2026
3e2c060
OpenConceptLab/ocl_online#798 | Simplification review: one statement …
paynejd Dec 1, 2026
f751a6a
OpenConceptLab/ocl_online#798 | A ValueSet written through FHIR keeps…
paynejd Dec 1, 2026
2c4026a
OpenConceptLab/ocl_online#798 | A FHIR update's new version takes its…
paynejd Dec 1, 2026
5a3e814
OpenConceptLab/ocl_online#798 | A ValueSet's clauses read back apart;…
paynejd Dec 1, 2026
5cb0d96
OpenConceptLab/ocl_online#798 | Merge fhir-452-b9-codesystem's review…
paynejd Dec 1, 2026
d17066c
OpenConceptLab/ocl_online#798 | A ValueSet update's compose replaces …
paynejd Dec 1, 2026
ca88563
OpenConceptLab/ocl_online#798 | A ValueSet update's compose replaces …
paynejd Dec 1, 2026
6da6861
OpenConceptLab/ocl_online#798 | Simplification review: no unreachable…
paynejd Dec 1, 2026
e8bdd67
OpenConceptLab/ocl_online#798 | A refused ValueSet update leaves HEAD…
paynejd Dec 1, 2026
497a262
OpenConceptLab/ocl_online#452 | Merge fhir-452-b-codes's new head int…
paynejd Dec 1, 2026
e5fd49f
OpenConceptLab/ocl_online#452 | Merge fhir-452-c-core (supplements an…
paynejd Dec 1, 2026
c85e972
OpenConceptLab/ocl_online#452 | Renumber collections/0079_value_set_c…
paynejd Dec 1, 2026
dc3b46a
OpenConceptLab/ocl_online#452 | Merge fhir-452-c-core's new head into…
paynejd Dec 1, 2026
8774060
OpenConceptLab/ocl_online#452 | collections/0081 bounds its lock wait…
paynejd Dec 1, 2026
9bd204b
OpenConceptLab/ocl_online#452 | Merge fhir-452-c-core's new head into…
paynejd Dec 1, 2026
be39526
OpenConceptLab/ocl_online#452 | Merge fhir-452-c-core's new head into…
paynejd Dec 1, 2026
5882ce3
OpenConceptLab/ocl_online#452 | collections/0081 bounds its lock wait…
paynejd Dec 1, 2026
6fdb855
OpenConceptLab/ocl_online#452 | Merge fhir-452-c-core's new head into…
paynejd Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 57 additions & 33 deletions core/capabilities/tests/test_make_private.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,19 @@
from core.capabilities.writes import makes_private
from core.code_systems.serializers import CodeSystemDetailSerializer
from core.collections.models import Collection
from core.collections.serializers import CollectionCreateOrUpdateSerializer
from core.collections.tests.factories import OrganizationCollectionFactory
from core.common.models import CelerySignalProcessor
from core.common.constants import ACCESS_TYPE_NONE, ACCESS_TYPE_VIEW, ROLE_ADMIN_ID
from core.common.tests import OCLAPITestCase, OCLAPITransactionTestCase
from core.concepts.tests.factories import ConceptFactory
from core.importers.importer import ImportRequest, ResourceImporter
from core.importers.models import BulkImportInline
from core.importers.models import BulkImportInline, UPDATED
from core.mappings.tests.factories import MappingFactory
from core.orgs.models import Organization
from core.orgs.tests.factories import OrganizationFactory
from core.sources.models import Source
from core.sources.serializers import SourceCreateOrUpdateSerializer
from core.sources.tests.factories import OrganizationSourceFactory, UserSourceFactory
from core.users.tests.factories import UserProfileFactory

Expand Down Expand Up @@ -248,26 +250,24 @@ def test_a_fhir_update_never_makes_a_private_head_viewable(self):
self.assertEqual(repo.versions.get(version=resource['version']).public_access, ACCESS_TYPE_NONE)
self.assertEqual([call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT])

def test_a_fhir_update_that_would_copy_a_private_release_onto_a_viewable_head_is_refused(self):
def test_a_fhir_update_keeps_a_viewable_head_s_access_whatever_the_release_s(self):
"""
It copies the release's other values too, so HEAD takes the release's access and asks make_private. A blank
access is private (public_can_view), so a blank release's is copied as it is, not as View.
The update saves onto HEAD from HEAD, not from the release the URL resolves, so a private release's access isn't
copied onto a viewable HEAD, nothing is asked about making HEAD private, and the new version, made from HEAD,
is viewable as HEAD is. A blank access is private (public_can_view) too.
"""
for release_access in (ACCESS_TYPE_NONE, ''):
for repo, factory, resource_type, extra in self.fhir_repositories():
kind = f'{type(repo).__name__.lower()}s'
with self.subTest(resource_type=resource_type, release_access=release_access):
response, resource = self.fhir_update(repo, factory, resource_type, release_access, **extra)

# FHIR routes answer every refusal as an OperationOutcome, with the body's message as its issue
self.assertEqual(response.status_code, 403, response.content)
self.assertEqual(response.json()['resourceType'], 'OperationOutcome')
self.assertEqual(
[item['details']['text'] for item in response.json()['issue']],
[PrivateGatePolicy.body['detail']])
self.assert_asked_to_make_private(self.take_calls(), row_id=repo.id)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual([call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT])
repo.refresh_from_db()
self.assertEqual(repo.public_access, ACCESS_TYPE_VIEW)
self.assertFalse(repo.versions.filter(version=resource['version']).exists())
self.assertTrue(repo.versions.get(version=resource['version']).public_can_view)
self.assertIn(repo.mnemonic, self.anonymous_list_ids(kind))

for release, version in (('r-None', 'v3'), ('r-', 'v4')):
with self.subTest(imported_onto=release):
Expand All @@ -277,30 +277,11 @@ def test_a_fhir_update_that_would_copy_a_private_release_onto_a_viewable_head_is
'version': version},
ImportRequest('orgs', self.org.mnemonic, self.user.username, 'CodeSystem'))

self.assertIsInstance(result, WriteRefused)
self.assertEqual(result.detail, PrivateGatePolicy.body)
self.assertEqual(result, UPDATED)
self.assertEqual([call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT])
self.source.refresh_from_db()
self.assertEqual(self.source.public_access, ACCESS_TYPE_VIEW)

def test_a_blank_release_the_policy_allows_leaves_head_and_the_new_version_private(self):
"""Stored as None, which the anonymous lists read as private too."""
PrivateGatePolicy.refuse = False
for repo, factory, resource_type, extra in self.fhir_repositories():
kind = f'{type(repo).__name__.lower()}s'
with self.subTest(resource_type=resource_type):
self.assertIn(repo.mnemonic, self.anonymous_list_ids(kind))

response, resource = self.fhir_update(repo, factory, resource_type, '', **extra)

self.assertEqual(response.status_code, 200, response.content)
# HEAD's row: the serializer then saves the same object as the new version, so it's not checked by id
self.assertEqual(
[call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT, WRITE_ACTION_MAKE_PRIVATE])
repo.refresh_from_db()
self.assertEqual(repo.public_access, ACCESS_TYPE_NONE)
self.assertFalse(repo.versions.get(version=resource['version']).public_can_view)
self.assertNotIn(repo.mnemonic, self.anonymous_list_ids(kind))

@staticmethod
def made_private_first(model, method, access=ACCESS_TYPE_NONE):
"""
Expand Down Expand Up @@ -330,6 +311,22 @@ def test_a_fhir_update_keeps_a_head_made_private_after_the_update_read_it(self):
self.assertEqual(repo.public_access, ACCESS_TYPE_NONE)
self.assertFalse(repo.versions.get(version=resource['version']).public_can_view)

def test_a_fhir_update_keeps_a_head_published_after_the_update_read_it(self):
"""The update keeps the access HEAD has when it's saved, so a publish since it read HEAD isn't undone"""
for repo, factory, resource_type, extra in self.fhir_repositories():
model = type(repo)
model.objects.filter(id=repo.id).update(public_access=ACCESS_TYPE_NONE)
with self.subTest(resource_type=resource_type):
with patch.object(
model, 'persist_changes', self.made_private_first(model, 'persist_changes', ACCESS_TYPE_VIEW)):
response, resource = self.fhir_update(repo, factory, resource_type, ACCESS_TYPE_NONE, **extra)

self.assertEqual(response.status_code, 200, response.content)
self.assertNotIn(WRITE_ACTION_MAKE_PRIVATE, [call[2] for call in self.take_calls()])
repo.refresh_from_db()
self.assertEqual(repo.public_access, ACCESS_TYPE_VIEW)
self.assertTrue(repo.versions.get(version=resource['version']).public_can_view)

def test_a_value_set_update_s_references_keep_a_head_made_private_after_head_was_saved(self):
"""Adding the resource's references saves HEAD again, after the lock: only who changed it, not its access."""
source = OrganizationSourceFactory(organization=self.org, canonical_url='http://example.org/cs')
Expand Down Expand Up @@ -369,6 +366,33 @@ def test_a_fhir_update_reads_head_for_update_in_the_transaction_that_saves_it(se
self.assertTrue(savepoint.startswith('SAVEPOINT '), savepoint)
self.assertGreater(sqls.index(f'RELEASE {savepoint}'), save)

@staticmethod
def counted(prepare_object, queries, calls):
"""`prepare_object`, recording in `calls` how many queries `queries` had captured at each call"""
def prepare(serializer, data, instance=None):
calls.append(len(queries.captured_queries))
return prepare_object(serializer, data, instance)
return prepare

def test_a_fhir_update_applies_the_resource_to_head_as_read_for_update(self):
"""So what it keeps of HEAD is HEAD as it is once locked, an edit committed before that included"""
for repo, factory, resource_type, extra in self.fhir_repositories():
row = f'"{type(repo)._meta.db_table}"."id" = {repo.id}' # pylint: disable=protected-access
klass = SourceCreateOrUpdateSerializer
if isinstance(repo, Collection):
klass = CollectionCreateOrUpdateSerializer
prepared_at = []
with self.subTest(resource_type=resource_type):
with CaptureQueriesContext(connection) as queries, patch.object(
klass, 'prepare_object', self.counted(klass.prepare_object, queries, prepared_at)):
response, _ = self.fhir_update(repo, factory, resource_type, ACCESS_TYPE_VIEW, **extra)

self.assertEqual(response.status_code, 200, response.content)
locks = [index for index, query in enumerate(queries.captured_queries) if
query['sql'].startswith('SELECT') and f'WHERE {row}' in query['sql'] and
query['sql'].endswith('FOR NO KEY UPDATE')]
self.assertTrue(locks and prepared_at and locks[0] < prepared_at[-1], (locks, prepared_at))

def test_a_rest_edit_that_sends_no_access_keeps_the_access_a_concurrent_write_gave_the_row(self):
"""
The edit saves the access its row has when it's saved, not the one the request read before: a row made private
Expand Down
8 changes: 3 additions & 5 deletions core/capabilities/tests/test_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.test import override_settings

from core.capabilities.constants import (
WRITE_ACTION_DELETE, WRITE_ACTION_EDIT, WRITE_ACTION_MAKE_PRIVATE, WRITE_ACTION_PUBLISH,
WRITE_ACTION_DELETE, WRITE_ACTION_EDIT, WRITE_ACTION_PUBLISH,
)
from core.capabilities.exceptions import WriteRefused
from core.capabilities.policy import GroupLimitPolicy
Expand Down Expand Up @@ -282,10 +282,8 @@ def test_a_fhir_update_is_asked_about_the_head_it_saves_onto(self):
response = self.request('put', f'{self.org.uri}CodeSystem/{self.source.mnemonic}/', resource)

self.assertEqual(response.status_code, 200, response.content)
# the update copies the private release's access onto HEAD, so it's asked about making HEAD private too
# (test_make_private), and that saved row is the new version by now
self.assertEqual(ReadOnlyPolicy.calls[0], (self.user, self.source, WRITE_ACTION_EDIT))
self.assertEqual([call[2] for call in ReadOnlyPolicy.calls[1:]], [WRITE_ACTION_MAKE_PRIVATE])
# HEAD keeps its own access, not the private release's, so it's only an edit (test_make_private)
self.assertEqual(ReadOnlyPolicy.calls, [(self.user, self.source, WRITE_ACTION_EDIT)])
ReadOnlyPolicy.calls = []
ResourceImporter.save_fhir_resource(
CodeSystemDetailSerializer, release, self.org, {**resource, 'version': 'v3'},
Expand Down
36 changes: 7 additions & 29 deletions core/code_systems/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,11 +282,12 @@ def get_resource_type(_):
def to_internal_value(self, data):
"""
Its concepts are written as the code system says (CodeSystemConceptField): whether it's a supplement, and its
language. An update that doesn't say keeps the stored ones.
language. An update that doesn't say keeps HEAD's, which it saves onto (update_head).
"""
head = get(self.instance, 'head')
self.context.update(
supplement=get(data, 'content', get(self.instance, 'content_type')) == CONTENT_TYPE_SUPPLEMENT,
language=get(data, 'language') or get(self.instance, 'default_locale') or settings.DEFAULT_LOCALE)
supplement=get(data, 'content', get(head, 'content_type')) == CONTENT_TYPE_SUPPLEMENT,
language=get(data, 'language') or get(head, 'default_locale') or settings.DEFAULT_LOCALE)
return super().to_internal_value(data)

def get_total_count(self, obj):
Expand Down Expand Up @@ -410,27 +411,7 @@ def update(self, instance, validated_data):
f' {instance.mnemonic}.'})
return instance

source = SourceCreateOrUpdateSerializer().prepare_object(validated_data, instance)

# Preserve version specific values
source_version = source.version
source_released = source.released

user = self.context['request'].user

# Update HEAD first
# Determine existing source ID
source_head = source.head
source.id = source_head.id
source.version = HEAD
source.released = False # HEAD must never be released
source.custom_validation_schema = source_head.custom_validation_schema
source.version_algorithm = source_head.version_algorithm # an R4 CodeSystem has no versionAlgorithm to write

# a FHIR resource carries no access: the update never makes a private HEAD viewable, but a private release's
# access goes onto a viewable HEAD with its other values, which asks make_private (ocl_online#698)
errors = Source.persist_changes(source, user, None, keep_private=True)

source, errors = self.update_head(instance, validated_data, SourceCreateOrUpdateSerializer().prepare_object)
if errors:
self._errors.update(errors)
return source
Expand All @@ -447,11 +428,8 @@ def update(self, instance, validated_data):
else:
Concept.persist_new(concept_serializer.validated_data)

# Create new version
source.version = source_version
source.released = source_released
source.id = None
# Make it synchronous for now so that the list of concepts is included in the response
errors = Source.persist_new_version(source, user, sync=True)
errors = Source.persist_new_version(
self.as_new_version(source, instance, validated_data), self.context['request'].user, sync=True)
self._errors.update(errors)
return source
8 changes: 4 additions & 4 deletions core/code_systems/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,15 +976,15 @@ def test_a_supplement_stored_without_supplements_stays_editable(self):
self.assertEqual(response.status_code, 200, response.data)
self.assertEqual(self.head().full_name, 'ICD-10 fr, edited')

def test_a_put_from_a_release_without_supplements_cant_clear_heads(self):
"""A FHIR PUT starts from the latest release: one stored without supplements can't clear the one HEAD has."""
def test_a_put_keeps_head_s_supplements_whatever_the_release_s(self):
"""A FHIR PUT starts from HEAD: a release stored without supplements doesn't clear the one HEAD has."""
self.assertEqual(self.write().status_code, 201)
Source.objects.filter(mnemonic='icd10-fr').exclude(version='HEAD').update(supplements=None)

response = self.write('put', version='2', supplements=None)
self.assertEqual(response.status_code, 400)
self.assertIn('supplements', str(response.data))
self.assertEqual(response.status_code, 200, response.data)
self.assertEqual(self.head().supplements, SUPPLEMENTED)
self.assertEqual(Source.objects.get(mnemonic='icd10-fr', version='2').supplements, SUPPLEMENTED)

def test_a_supplement_without_a_language_keeps_its_display_in_the_default_locale(self):
"""
Expand Down
4 changes: 3 additions & 1 deletion core/collections/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,10 @@ def get_system_version_namespace(owner_url):
return Expansion.get_system_version_namespace(owner_url)

def apply_parameters(self, queryset, is_concept_queryset):
"""As Expansion.apply_parameters: its parameters and the imported version's own rule on retired concepts"""
from core.collections.models import ExpansionParameters
return ExpansionParameters(self.parameters, is_concept_queryset).apply(queryset)
return ExpansionParameters.of_version(self.parameters, is_concept_queryset, self.collection_version).apply(
queryset)

@property
def concepts(self):
Expand Down
6 changes: 5 additions & 1 deletion core/collections/member_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,11 @@ def can_be(self, reference, version):

def held_at(self, version, candidates):
"""The candidates (concepts in `version`) it holds there, and those it holds by code (held_by_code). One that
leads back to a value set being evaluated again holds there only its own members in that version"""
leads back to a value set being evaluated again holds there only its own members in that version. Its own rule
on retired concepts (Collection.include_retired) leaves retired candidates out, as its build does"""
from core.collections.models import ExpansionParameters
if ExpansionParameters.leaves_retired_out(self.collection_version):
candidates = ExpansionParameters({}, True, retired_left_out=True).apply(candidates)
replaying = self.member_versions.replaying
if self.collection_version.id in replaying:
held = concepts_q([self.members_at(version)])
Expand Down
35 changes: 35 additions & 0 deletions core/collections/migrations/0081_value_set_compose_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Adds what a ValueSet written through FHIR says beyond its references: collections.include_retired, the value set's own
rule on retired (inactive) concepts, and collection_references.concept_details, a listed code's designations and
extensions. Both columns are nullable with no default, which PostgreSQL adds by updating the catalog only: no existing
row is read or rewritten.

Its lock waits are bounded (LOCK_TIMEOUT), as phase C's storage migrations' are: behind a long transaction on a table it
alters (collection_references, collections), it fails in seconds and changes nothing, instead of holding its locks,
and every query queued behind them, until that transaction ends. Run it again once that transaction is over.
"""
from django.db import migrations, models

LOCK_TIMEOUT = "SET LOCAL lock_timeout = '5s'" # within the migration's own transaction


class Migration(migrations.Migration):

dependencies = [
('collections', '0080_expansion_reserved_codes'),
]

operations = [
migrations.RunSQL(LOCK_TIMEOUT, reverse_sql=migrations.RunSQL.noop), # first, applied
migrations.AddField(
model_name='collection',
name='include_retired',
field=models.BooleanField(blank=True, default=None, null=True),
),
migrations.AddField(
model_name='collectionreference',
name='concept_details',
field=models.JSONField(blank=True, null=True),
),
migrations.RunSQL(migrations.RunSQL.noop, reverse_sql=LOCK_TIMEOUT), # first, reversed
]
Loading
Loading