Repository navigation
OpenConceptLab/ocl_issues#3003 | expansion health classifier (PR 1 of 4) - #1025
snyaggarwal wants to merge 9 commits into
Conversation
…mber's class, the expansion's state, reasons and counts
snyaggarwal
left a comment
There was a problem hiding this comment.
Verdict: approve once CI is green and the production EXPLAIN is checked. Nothing is blocking: five non-blocking notes, inline.
The classifier follows the design and the nine decisions as made on Nov 23.
- Members: a member is attributed by its versioned object, judged against the repo versions its reference resolved to, checked for containment in one query per kind (source membership, or the value set's default expansion), and combined into
ambiguouswhen references disagree. - Reasons and state come straight from the recorded lists and
unresolved_repo_versions, in the design's order. - It's read-only: nothing is written, and no member changes.
- Query count: it doesn't grow with references; the toggle is read once for all of them, and a test checks it.
Non-blocking notes:
inconsistent_resolutionalways fires together withduplicate_repo_versions, because every unversioned reference reads its versions from the same recorded per-repository list.- Unrecorded value sets are judged against their latest release, not the lock, because the value-set cache resolves that way.
- A member of an unreleased named version is counted as
release. - No test classifies a mapping member.
- Old expansions' recorded lists aren't reliable until OpenConceptLab/ocl_issues#3005 runs, so #3005 should run before this ticket's backfill (PR 4).
Before merge: a read-only EXPLAIN on production for SM-CON-SET 1.0.1. It checks that the attribution join doesn't fall back to a full scan of collections_referencedconcept.
CI: Snyk passed and Pylint is pending. The tests haven't run on this commit yet; the local oclapi2 stack is down.
| repositories[drop_version(uri)] = (version_ids | {version_id}, from_unversioned or is_evaluated) | ||
| return repositories | ||
|
|
||
| def get_inconsistent_repositories(self): |
There was a problem hiding this comment.
Nit (optional): inconsistent_resolution always fires together with duplicate_repo_versions. Every unversioned reference reads its versions from the expansion's recorded per-repository list (get_source_versions_resolved_by), so all of them get the same list. It can't tell two references that really resolved to different versions apart from a repository recorded at two versions, and every such case is reported twice.
Either:
- judge it from each reference's own resolved resources, i.e. which source versions hold its members, or
- drop it as a separate reason and say in the design that
duplicate_repo_versionscovers it.
| return {reference.id: reference for reference in self.references if reference.include} | ||
|
|
||
| @cached_property | ||
| def resolved_versions(self): |
There was a problem hiding this comment.
Nit (optional): unrecorded value sets are judged against their latest release, not the lock. With valueset_version_cache passed, _get_valueset_version resolves to the latest release. When the expansion recorded nothing for an unversioned value set, as on expansions built before #3002, its members are judged against that latest release. If the release has changed since, they show as version mismatches.
Either:
- resolve those few references without the cache (under the collection's lock), or
- document that such members may show as mismatches until a rebuild.
| if self.version_key(version) in containments.get(member_id, set()) | ||
| ] | ||
| if holders: | ||
| return HEAD_MEMBER if all(version.version == HEAD for version in holders) else RELEASE |
There was a problem hiding this comment.
Nit (optional): an unreleased named version is counted as release. When the version a reference names isn't released (e.g. /v1-draft/) but holds the member, this branch still returns release. TBv3 (#3004) would then show it as a member of a release.
Either:
- rename the class to something neutral like
resolved, or - add a class for unreleased versions.
At least note it in the design's class table.
| from core.sources.tests.factories import OrganizationSourceFactory | ||
|
|
||
|
|
||
| class ExpansionHealthTest(OCLTestCase): |
There was a problem hiding this comment.
Nit (optional): no test classifies a mapping member. Decision 4 says mappings use the same rules from day one, but none of these paths is tested with a mapping:
ReferencedMappingattribution- the mapping sources table
Expansion.mappingsin the value-set containment
One test with a mapping held by a release, plus one mismatch, would cover them.
| classes[member[0]] = (member_class, reference_ids, member[0] == member[1]) | ||
| return classes | ||
|
|
||
| def get_repository_versions(self): |
There was a problem hiding this comment.
Nit (optional): this depends on #3005 for old expansions. The repository reasons and unversioned resolution read the recorded explicit_* / evaluated_* lists. Expansions built before locking list every version as explicit, and some list a version in both lists. That's what OpenConceptLab/ocl_issues#3005 rebuilds.
If PR 4's backfill runs first, many old expansions will show inconsistent_resolution or multiple_named_versions that only reflect those lists. Run #3005 before the backfill, and say so in the plan.
…the versions each reference's members came from; unreleased class; mapping tests
|
Review notes addressed in 50eee87. The PR description and the design doc are updated.
|
snyaggarwal
left a comment
There was a problem hiding this comment.
Second review (50eee87). Verdict: approve once CI is green and the production EXPLAIN is checked. Nothing is blocking; one nit inline.
The first review's notes are resolved:
inconsistent_resolutionnow follows which resolved versions hold each unversioned reference's members. A repository merely recorded at two versions is only a duplicate, and both cases are tested.unreleasedis its own healthy class, soreleasemeans a released holder.- Mappings are tested, including
head_mapping. - The #3005 ordering is in the description and the design.
- The value-set point needed no change: the lock is the same recorded list.
Also re-checked:
versions_used_by_referenceonly accumulates. A page classification followed by a full one gives the same result, and it adds no queries, so the query-bound test still holds.judgestill classes a HEAD object as a mismatch before the release check, and it returns its holders, so they still count toward inconsistency.
Nit: a HEAD object that ends up ambiguous isn't counted in head_concept / head_mapping.
CI: Snyk passed and Pylint is pending. The tests haven't reported on this commit yet.
| head_counts[resource_type] = 0 | ||
| for member_class, _, is_head_object in classes.values(): | ||
| counts[member_class] += 1 | ||
| if member_class == MISMATCH and is_head_object: |
There was a problem hiding this comment.
Nit (optional): a HEAD object that ends up ambiguous drops out of the sub-count. Only members whose final class is mismatch are counted. A HEAD concept that's both pinned by a resource-versioned reference and reached by an unversioned one becomes ambiguous, so head_concept reports 0. Since a HEAD object is never a valid member, count it regardless of its final class:
| if member_class == MISMATCH and is_head_object: | |
| if is_head_object: |
Then head_concept / head_mapping is the number of HEAD objects among the members. They stay attached to version_mismatches in the reasons; consider moving them to the top level of members if a HEAD object can be ambiguous.
…ed apart whether they end up a mismatch or ambiguous
|
The nit is fixed in the latest commit, in a slightly wider form than the suggestion. HEAD concepts and mappings are now counted per class, and both New test: a HEAD concept reached by an unversioned reference and pinned by a resource-versioned one. It's |
snyaggarwal
left a comment
There was a problem hiding this comment.
Third review (0dc89cb). Verdict: approved, ready to merge once CI is green and the production EXPLAIN is checked. No open findings.
- Last change: HEAD concepts and mappings are now counted per class.
version_mismatchesandambiguous_membersboth carryhead_concept/head_mapping, so a HEAD object that references judge differently is still named. The existing mismatch assertions keep their exact shape, and the new test covers the ambiguous case. - Across the three rounds: the classifier follows the design and the nine decisions of Nov 23, with these additions:
- the
unreleasedclass inconsistent_resolutionjudged from where each reference's members came from- HEAD sub-counts on mismatch and ambiguous members
- the
- Unchanged guarantees: it writes nothing and changes no member. Its query count doesn't grow with references.
Before merge:
- CI green. The test suite hasn't completed on any commit of this PR yet: each push restarted the run, and the local oclapi2 stack is down. Snyk passed; Pylint is pending.
- The read-only production
EXPLAINfor SM-CON-SET 1.0.1 (38,363 members). It checks that the attribution join (collections_referencedconceptagainst the expansion's members) doesn't fall back to a full scan.
After merge: PR 2 adds the storage and the triggers. OpenConceptLab/ocl_issues#3005 must run on production before PR 4's backfill.
…members their versions don't hold, by id in batches, so mappings_sources isn't scanned
|
Production
The fix: that check now runs only for members that none of their references' resolved versions hold. Only those can be interim or a mismatch.
New tests:
|
snyaggarwal
left a comment
There was a problem hiding this comment.
Fourth review (478d894). Verdict: approved, ready to merge once CI is green. No open findings.
Last change: "held by a release or HEAD" now runs only for members that some reference judges that way. Those are members that aren't HEAD objects, attributed to a non-resource-versioned reference, and held by none of that reference's resolved versions. That's exactly when judge reads the result, so classes don't change. The lookup goes by id in batches of 10,000 instead of a subquery of every member, which is what made the planner scan mappings_sources on production. A healthy expansion skips it entirely. The query-bound test still holds, and two new tests cover the skip and the batching.
Across the review rounds: the classifier follows the design and the Nov 23 decisions. Additions from review:
- the
unreleasedclass - per-reference
inconsistent_resolution - HEAD sub-counts on mismatch and ambiguous members
- the batched check
It writes nothing and changes no member. The production EXPLAIN showed index plans for attribution and containment.
Before merge:
- CI green. The test suite still hasn't completed on any commit of this PR. Snyk passed; Pylint is pending.
- Optional: confirm the batched lookup's plan on production. That's query 6 from the
EXPLAINwith up to 10,000 literal member ids instead of the subquery. It should usemappings_sources_mapping_id.
After merge: PR 2 (storage and triggers). OpenConceptLab/ocl_issues#3005 runs on production before PR 4's backfill.
… can see decide interim from mismatch; a value set with no default expansion is a reason; more tests
paynejd
left a comment
There was a problem hiding this comment.
Review at d050ab5. An independent defect pass (Codex, high effort), with every finding checked against the code before it went here. Points from today's earlier reads that you've already fixed aren't repeated.
Verdict: approve. Nothing here blocks the merge while the health toggle is off. The points below are worth fixing before the toggle goes on in production, in this PR or a follow-up.
Worth fixing before the toggle goes on
- Manual (non-default) expansions read as unattributed. Attribution uses
ReferencedConcept/ReferencedMappingrows only (health.py~100-110). Only the default expansion's build writes those rows (theshould_write_backbranch inmodels.py~1920), and none are written when auto-expand is off. #1026 stores health for every build, so a manual expansion's members come outunattributedand the expansionunhealthyalthough its references produced them. Decided today: compute and store health only for a version's default expansion for now, and return null for the others. - Visibility filter: use the API's own rule.
get_visible_source_filter(~163-170) counts a version as public from its ownpublic_access. Master'sis_publicly_viewablealso needs the HEAD to be public, because versions keep their flag when the HEAD goes private. Same one-bit hint as the earlier point, in the case where the source owner later makes the source private. The same rule is needed in #1032 (publicon the deleted-lock record) and #1033 (is_visible). - A retired, explicitly named value-set version drops out.
_get_resolved_valueset_versionsresolves live (models.py~1477-1497). For a relative versioned URI, that filtersretired=False, so once the named version is retired the reference resolves to nothing, and its members become mismatch or interim on the next recompute. That goes against "retiring a release doesn't change the lock". Fix: match explicit value-set entries against the expansion's recordedexplicit_collection_versionsfirst. - Named value-set versions trip
inconsistent_resolution.get_inconsistent_repositories(~259-261) keeps any reference whereis_versionless_expressionis true. A value-set-only reference namingVS/v1/has noversion, so it counts as unversioned, while the build records it as explicit. Two such references naming different versions make the expansion unhealthy, against decision 1. Suggestion inline; please add a test with two named value-set versions. - A HEAD carrying the legacy
releasedflag counts as a release (judge, ~211). Its HEAD-only members come outreleaseinstead ofhead. The state stayshead_resolved, but the class and counts are wrong. Suggestion inline. - Excludes against a value set with no expansion aren't reported.
value_set_without_expansionlooks at include references only (~67-78, ~185-193). An exclude like that silently excludes nothing, and the expansion can read healthy. Count excludes in that reason too, and keep member judgement to includes. - Pinned members get their real class too.
judge(~199) returnsresource_versionedfor every member of a pinned reference without looking further, so a pinned version that sits in no release never shows as interim. Interim versions are never hidden (ocl_issues#2942), so judge these members like the rest: against the releases and HEAD of the reference's repository that hold them (#1033'sget_repo_versions_holding_resource_versionsdoes that lookup). The expansion keeps itsresource_versioned_referencesreason, so it still reads unhealthy.
Minor
- Taking the union of holders per reference (~234) can hide
inconsistent_resolutionin one case.duplicate_repo_versionsstill fires, so the state doesn't change. Optional.
Still open with Jon: whether an expansion that names a never-released version (class unreleased) counts as healthy. Keep it as built until he answers. It's rare in production.
| if member_id == versioned_object_id: | ||
| # a HEAD concept or mapping is never a valid member | ||
| return MISMATCH, holder_keys | ||
| if any(version.released for version in holders): |
There was a problem hiding this comment.
Point 5: a HEAD carrying the legacy released flag no longer counts as a release.
| if any(version.released for version in holders): | |
| if any(version.released and version.version != HEAD for version in holders): |
| if not self.include_references[reference_id].is_versionless_expression: | ||
| continue |
There was a problem hiding this comment.
Point 4: a value-set-only reference that names a version of each of its value sets is skipped, as the build records it explicit.
| if not self.include_references[reference_id].is_versionless_expression: | |
| continue | |
| reference = self.include_references[reference_id] | |
| # a value-set-only reference that names each value set's version is explicit, as the build records it | |
| if not reference.is_versionless_expression or (not reference.system and all( | |
| reference.is_explicit_valueset(valueset) for valueset in reference.valueset or [] if valueset)): | |
| continue |
paynejd
left a comment
There was a problem hiding this comment.
Follow-up on the unreleased class, now that the model call is made. This replaces my approval; everything else in it stands.
A member held only by an unreleased named version should make the expansion unhealthy, not healthy. OCL doesn't support references that resolve to an unreleased version yet: same-owner references to one are planned, but not built. Until then, the owner needs to see it and get the chance to change the reference.
- Keep the
unreleasedclass: the label is right. - Give it a reason,
unreleased_versions, so the expansion readsunhealthy(suggestion inline). Rename it if you like; the TBv3 badge (ocl_issues#3004) will need wording for it. - The test changes with it (suggestion inline), and so does the PR text: rule 3 says "which is healthy".
Nothing later in the stack relies on unreleased being healthy: I checked through #1032.
| SYSTEM_VERSION_PARAMETER_TYPE = 'expansion.parameters.system-version' | ||
| RESOURCE_TYPES = ('concepts', 'mappings') | ||
| MEMBER_REASONS = ( | ||
| (INTERIM, 'interim_resource_versions'), |
There was a problem hiding this comment.
Counts members held only by an unreleased version as a problem, so the expansion reads unhealthy.
| (INTERIM, 'interim_resource_versions'), | |
| (UNRELEASED, 'unreleased_versions'), | |
| (INTERIM, 'interim_resource_versions'), |
| self.reference(concept, version, version='draft') | ||
|
|
||
| self.assertEqual(self.classify(), {version.id: UNRELEASED}) | ||
| self.assertEqual(self.health()['state'], HEALTHY) |
There was a problem hiding this comment.
The test now expects unhealthy, with the new reason.
| self.assertEqual(self.health()['state'], HEALTHY) | |
| health = self.health() | |
| self.assertEqual(health['state'], UNHEALTHY) | |
| self.assertEqual(self.reason_codes(health), {'unreleased_versions': 1}) |
…nned members get their real class, and a page resolves only its own references
|
Thanks, Jon. Both reviews are addressed in e89e9c5, which sits on a merge of master (e027800). The description is updated.
From #1029, point 5: The local Elasticsearch container is down, so CI is the first test run; pylint is clean. |
paynejd
left a comment
There was a problem hiding this comment.
Thanks, Sunny. Every point is met, including the unreleased_versions reason. A page now resolves only its own references, and gives each member the same class a full run does.
CI fails two tests that still expect the removed resource_versioned class (failures=2). Suggestions inline:
test_head_concept_judged_differently_is_ambiguous_and_still_counted_apart: every reference now judges a HEAD concept a mismatch, so it can't be ambiguous.test_member_two_references_judge_differently_is_ambiguous: the pinned reference now says release too. The suggestion makes the references disagree again. The unversioned one resolves to v2, which doesn't hold the old version; the pinned one finds it in release v1.
Before health is turned on in production: a pinned repository's cost grows with its number of versions (point 7).
is_visiblereads each public version's HEAD throughis_publicly_viewable, one query per version. The lookup is keyed by the named version, so it repeats for every version a reference names.get_containmentsputs every visible version of a pinned repository into the membership query for all members. An unchanged concept version sits in every version of its source, so rows grow as members × versions. A large collection that pins a source with many versions loads millions of rows per compute, both in the build'supdate_healthand in the backfill.- Suggestions inline, four that go together:
- one query per repository, filtered with
get_viewable_versions_criteria(None) | ownerand keyed by (system, namespace); - a pinned repository's other versions read only for the members a pinned reference judges.
- one query per repository, filtered with
- Keying by repository also fixes a smaller gap. Today, if the version a reference names has since been deleted, its members read interim even when HEAD or a release holds them.
- All six suggestions compile and pass pylint together. I traced them against the code but couldn't run them.
Smaller, no action needed:
- No test covers a pinned member held only by another owner's private release (it should read interim), or only by HEAD, or only by an unreleased version.
ambiguous_members' HEAD counts are now always 0.get_attributionsloads all of the version's references for each page throughself.references. It's one query and resolves nothing, but it grows with the collection.
| def test_head_concept_judged_differently_is_ambiguous_and_still_counted_apart(self): | ||
| head_concept = ConceptFactory(parent=self.source) | ||
| self.reference(head_concept, head_concept) | ||
| pinned = CollectionReference( | ||
| expression=head_concept.uri, collection=self.collection, system=self.source.uri, | ||
| code=head_concept.mnemonic, resource_version=head_concept.version) | ||
| pinned.save() | ||
| pinned.concepts.add(head_concept) | ||
|
|
||
| self.assertEqual(self.classify(), {head_concept.id: AMBIGUOUS}) | ||
| ambiguous = next(reason for reason in self.health()['reasons'] if reason['code'] == 'ambiguous_members') | ||
| self.assertEqual(ambiguous, {'code': 'ambiguous_members', 'count': 1, 'head_concept': 1, 'head_mapping': 0}) |
There was a problem hiding this comment.
Every reference, pinned or not, now judges a HEAD concept a mismatch.
| def test_head_concept_judged_differently_is_ambiguous_and_still_counted_apart(self): | |
| head_concept = ConceptFactory(parent=self.source) | |
| self.reference(head_concept, head_concept) | |
| pinned = CollectionReference( | |
| expression=head_concept.uri, collection=self.collection, system=self.source.uri, | |
| code=head_concept.mnemonic, resource_version=head_concept.version) | |
| pinned.save() | |
| pinned.concepts.add(head_concept) | |
| self.assertEqual(self.classify(), {head_concept.id: AMBIGUOUS}) | |
| ambiguous = next(reason for reason in self.health()['reasons'] if reason['code'] == 'ambiguous_members') | |
| self.assertEqual(ambiguous, {'code': 'ambiguous_members', 'count': 1, 'head_concept': 1, 'head_mapping': 0}) | |
| def test_head_concept_a_pinned_reference_names_is_still_a_mismatch(self): | |
| head_concept = ConceptFactory(parent=self.source) | |
| self.reference(head_concept, head_concept) | |
| pinned = CollectionReference( | |
| expression=head_concept.uri, collection=self.collection, system=self.source.uri, | |
| code=head_concept.mnemonic, resource_version=head_concept.version) | |
| pinned.save() | |
| pinned.concepts.add(head_concept) | |
| # every reference, pinned or not, judges a HEAD concept a mismatch | |
| self.assertEqual(self.classify(), {head_concept.id: MISMATCH}) | |
| mismatch = next(reason for reason in self.health()['reasons'] if reason['code'] == 'version_mismatches') | |
| self.assertEqual(mismatch, {'code': 'version_mismatches', 'count': 1, 'head_concept': 1, 'head_mapping': 0}) |
| def test_member_two_references_judge_differently_is_ambiguous(self): | ||
| concept = ConceptFactory(parent=self.source) | ||
| version = concept.get_latest_version() | ||
| release = self.release('v1', version) | ||
| self.expansion.evaluated_source_versions.add(release) | ||
| self.reference(concept, version) | ||
| pinned = CollectionReference( | ||
| expression=version.uri, collection=self.collection, system=self.source.uri, code=concept.mnemonic, | ||
| resource_version=version.version) | ||
| pinned.save() | ||
| pinned.concepts.add(version) | ||
|
|
||
| classes = ExpansionHealth(self.expansion).classify('concepts') | ||
| self.assertEqual(classes[version.id][0], AMBIGUOUS) | ||
| self.assertEqual(len(classes[version.id][1]), 2) | ||
| self.assertEqual(self.reason_codes(self.health())['ambiguous_members'], 1) |
There was a problem hiding this comment.
The references disagree again: the unversioned one resolves to v2, which doesn't hold the old version, and the pinned one finds it in release v1.
| def test_member_two_references_judge_differently_is_ambiguous(self): | |
| concept = ConceptFactory(parent=self.source) | |
| version = concept.get_latest_version() | |
| release = self.release('v1', version) | |
| self.expansion.evaluated_source_versions.add(release) | |
| self.reference(concept, version) | |
| pinned = CollectionReference( | |
| expression=version.uri, collection=self.collection, system=self.source.uri, code=concept.mnemonic, | |
| resource_version=version.version) | |
| pinned.save() | |
| pinned.concepts.add(version) | |
| classes = ExpansionHealth(self.expansion).classify('concepts') | |
| self.assertEqual(classes[version.id][0], AMBIGUOUS) | |
| self.assertEqual(len(classes[version.id][1]), 2) | |
| self.assertEqual(self.reason_codes(self.health())['ambiguous_members'], 1) | |
| def test_member_two_references_judge_differently_is_ambiguous(self): | |
| concept, old, new = self.concept_with_replaced_version() | |
| self.release('v1', old) | |
| self.expansion.evaluated_source_versions.add(self.release('v2', new)) | |
| self.reference(concept, old) | |
| pinned = CollectionReference( | |
| expression=old.uri, collection=self.collection, system=self.source.uri, code=concept.mnemonic, | |
| resource_version=old.version) | |
| pinned.save() | |
| pinned.concepts.add(old) | |
| # the unversioned reference resolved to v2, which doesn't hold it; the pinned one finds it in release v1 | |
| classes = ExpansionHealth(self.expansion).classify('concepts') | |
| self.assertEqual(classes[old.id][0], AMBIGUOUS) | |
| self.assertEqual(len(classes[old.id][1]), 2) | |
| self.assertEqual(self.reason_codes(self.health())['ambiguous_members'], 1) |
| self._repo_versions = {} | ||
| self._visible = {} |
There was a problem hiding this comment.
(1 of 4) With 2 of 4, no per-version visibility cache is needed.
| self._repo_versions = {} | |
| self._visible = {} | |
| self._repo_versions = {} |
| def is_visible(self, repo_version): | ||
| """Whether the collection's owner can view it: publicly viewable (its HEAD public too) or the owner's own. | ||
| Once per version, as is_publicly_viewable reads the HEAD""" | ||
| if repo_version.id not in self._visible: | ||
| version = self.collection_version | ||
| if version.organization_id: | ||
| owned = repo_version.organization_id == version.organization_id | ||
| else: | ||
| owned = repo_version.user_id == version.user_id | ||
| self._visible[repo_version.id] = owned or repo_version.is_publicly_viewable | ||
| return self._visible[repo_version.id] | ||
|
|
||
| def get_pinned_versions(self, reference_id): | ||
| """The active versions of a resource-versioned reference's repository its owner can view: its members are | ||
| judged by which of them hold them, as any member is. Looked up once per repository""" | ||
| from core.sources.models import Source | ||
| if reference_id not in self._pinned_versions: | ||
| reference = self.include_references[reference_id] | ||
| key = (reference.system, reference.resolution_namespace, reference.version) | ||
| if key not in self._repo_versions: | ||
| repo_version, _ = Source.resolve_reference_expression(*key) if reference.system else (None, None) | ||
| self._repo_versions[key] = [ | ||
| version for version in repo_version.active_versions if self.is_visible(version) | ||
| ] if repo_version and repo_version.id else [] | ||
| self._pinned_versions[reference_id] = self._repo_versions[key] | ||
| return self._pinned_versions[reference_id] |
There was a problem hiding this comment.
(2 of 4) One query per repository, filtered to what the owner can view, whichever version a reference names.
| def is_visible(self, repo_version): | |
| """Whether the collection's owner can view it: publicly viewable (its HEAD public too) or the owner's own. | |
| Once per version, as is_publicly_viewable reads the HEAD""" | |
| if repo_version.id not in self._visible: | |
| version = self.collection_version | |
| if version.organization_id: | |
| owned = repo_version.organization_id == version.organization_id | |
| else: | |
| owned = repo_version.user_id == version.user_id | |
| self._visible[repo_version.id] = owned or repo_version.is_publicly_viewable | |
| return self._visible[repo_version.id] | |
| def get_pinned_versions(self, reference_id): | |
| """The active versions of a resource-versioned reference's repository its owner can view: its members are | |
| judged by which of them hold them, as any member is. Looked up once per repository""" | |
| from core.sources.models import Source | |
| if reference_id not in self._pinned_versions: | |
| reference = self.include_references[reference_id] | |
| key = (reference.system, reference.resolution_namespace, reference.version) | |
| if key not in self._repo_versions: | |
| repo_version, _ = Source.resolve_reference_expression(*key) if reference.system else (None, None) | |
| self._repo_versions[key] = [ | |
| version for version in repo_version.active_versions if self.is_visible(version) | |
| ] if repo_version and repo_version.id else [] | |
| self._pinned_versions[reference_id] = self._repo_versions[key] | |
| return self._pinned_versions[reference_id] | |
| def get_pinned_versions(self, reference_id): | |
| """The active versions of a resource-versioned reference's repository its owner can view: publicly viewable | |
| (their HEAD public too) or the owner's own. Its members are judged by which of them hold them, as any member | |
| is. One query per repository, whichever version a reference names""" | |
| from core.sources.models import Source | |
| if reference_id not in self._pinned_versions: | |
| reference = self.include_references[reference_id] | |
| key = (reference.system, reference.resolution_namespace) | |
| if key not in self._repo_versions: | |
| repo_version, _ = Source.resolve_reference_expression(*key) if reference.system else (None, None) | |
| version = self.collection_version | |
| owner = Q(organization_id=version.organization_id) if version.organization_id else Q( | |
| user_id=version.user_id) | |
| self._repo_versions[key] = list(repo_version.active_versions.filter( | |
| Source.get_viewable_versions_criteria(None) | owner)) if repo_version and repo_version.id else [] | |
| self._pinned_versions[reference_id] = self._repo_versions[key] | |
| return self._pinned_versions[reference_id] |
| def get_containments(self, resource_type, members, reference_ids): | ||
| """{member id: keys of the repo versions these references resolved to, or are pinned in, that hold it}""" | ||
| resource, klass, _ = self.get_resource_models(resource_type) | ||
| versions = self.get_candidate_versions(reference_ids) | ||
| source_ids = [version_id for kind, version_id in versions if kind == 'source'] | ||
| containments = {} | ||
| if source_ids: | ||
| rows = klass.sources.through.objects.filter( | ||
| source_id__in=source_ids, **{f'{resource}_id__in': members.values('id')} | ||
| ).values_list(f'{resource}_id', 'source_id') | ||
| for member_id, source_id in rows: | ||
| containments.setdefault(member_id, set()).add(('source', source_id)) | ||
| self.add_value_set_containments(resource_type, members, versions, containments) | ||
| return containments |
There was a problem hiding this comment.
(3 of 4) A pinned repository's other versions are read only for the members a pinned reference judges.
| def get_containments(self, resource_type, members, reference_ids): | |
| """{member id: keys of the repo versions these references resolved to, or are pinned in, that hold it}""" | |
| resource, klass, _ = self.get_resource_models(resource_type) | |
| versions = self.get_candidate_versions(reference_ids) | |
| source_ids = [version_id for kind, version_id in versions if kind == 'source'] | |
| containments = {} | |
| if source_ids: | |
| rows = klass.sources.through.objects.filter( | |
| source_id__in=source_ids, **{f'{resource}_id__in': members.values('id')} | |
| ).values_list(f'{resource}_id', 'source_id') | |
| for member_id, source_id in rows: | |
| containments.setdefault(member_id, set()).add(('source', source_id)) | |
| self.add_value_set_containments(resource_type, members, versions, containments) | |
| return containments | |
| def get_containments(self, resource_type, members, reference_ids, pinned_member_ids): | |
| """{member id: keys of the repo versions these references resolved to, or are pinned in, that hold it}. A pinned | |
| repository's other versions are read only for the members a pinned reference judges: an unchanged concept or | |
| mapping version sits in every version of its source""" | |
| resource, klass = self.get_resource_models(resource_type)[:2] | |
| versions = self.get_candidate_versions(reference_ids) | |
| resolved_ids = { | |
| version.id for resolved in self.resolve(reference_ids).values() for version in resolved | |
| if self.version_key(version)[0] == 'source'} | |
| pinned_ids = {version_id for kind, version_id in versions if kind == 'source'} - resolved_ids | |
| containments = {} | |
| for source_ids, member_ids in ((resolved_ids, members.values('id')), (pinned_ids, pinned_member_ids)): | |
| if source_ids: | |
| for member_id, source_id in klass.sources.through.objects.filter( | |
| source_id__in=list(source_ids), **{f'{resource}_id__in': member_ids} | |
| ).values_list(f'{resource}_id', 'source_id'): | |
| containments.setdefault(member_id, set()).add(('source', source_id)) | |
| self.add_value_set_containments(resource_type, members, versions, containments) | |
| return containments | |
| def get_pinned_member_ids(self, member_rows, attributions): | |
| """Members some resource-versioned reference judges""" | |
| pinned = {reference.id for reference in self.include_references.values() if reference.is_resource_versioned} | |
| return [ | |
| member_id for member_id, versioned_object_id in member_rows | |
| if pinned & attributions.get(versioned_object_id, set())] |
| containments = self.get_containments( | ||
| resource_type, members, sorted(set().union(*attributions.values()) if attributions else set())) |
There was a problem hiding this comment.
(4 of 4) Passes those members in.
| containments = self.get_containments( | |
| resource_type, members, sorted(set().union(*attributions.values()) if attributions else set())) | |
| containments = self.get_containments( | |
| resource_type, members, sorted(set().union(*attributions.values()) if attributions else set()), | |
| self.get_pinned_member_ids(member_rows, attributions)) |
…ns that judge a member differently, and a HEAD concept stays a mismatch
|
CI fix (cc52b86): two ambiguity tests still assumed a pinned reference gives a class of its own. Since pinned members get their real class, a HEAD concept is a mismatch under every reference, so it can't be ambiguous. That test now asserts it stays a mismatch. The other test now builds a member that two references named at |
paynejd
left a comment
There was a problem hiding this comment.
Review lead (Claude, for Jon), round 3
Thanks, Sunny. Both test fixes are right. A HEAD concept is a mismatch whichever reference judges it, so it can't be ambiguous. The v1/draft pair gives one member two references that judge it differently. CI is green at cc52b86. Every round-2 point is met.
Approved for merge. On its own this PR adds the classifier with no caller outside its tests, so merging it changes nothing in production.
Still needed before health is turned on in production: round 2's cost fix (the four suggestions on health.py, or your own).
- A pinned repository's versions still go into the membership query for every member.
is_visiblestill reads one HEAD per version.- Land it in this PR or in a follow-up linked here. Health stays off until it does.
…ead in one query and only for the members a pinned reference judges
|
Round 2's cost fix is in this PR (fc2262b). It follows your four suggestions, with two changes noted below.
Two new tests:
Your round-2 test suggestions had already been met in cc52b86. Not done, from the smaller notes: tests for a pinned member held only by a private release, only by HEAD or only by an unreleased version; the always-zero HEAD counts in |
PR 1 of 4 for OpenConceptLab/ocl_issues#3003 (epic OpenConceptLab/ocl_issues#2942): the classifier. It doesn't store anything, add an endpoint or change any member. Those are PRs 2–4 in the design. The design's 9 decisions were made on Nov 23, each as recommended.
ExpansionHealth(expansion)incore/collections/health.py:classify(resource_type, member_ids=None): returns{member id: (class, ids of the references that judged it, is a HEAD object)}for all members or for a page of them. A page resolves only the references its members are attributed to, and an empty page does no work. PR 3's?includeHealth=truewill use it.compute(): returns the summary that PR 2 will store, in the design's shape:state,reasons, per-class counts for concepts and mappings,head_resolved_repositories,multiple_named_versions,rules_version: 1andcomputed_at.How a member is classed
It reuses what the expansion already recorded; nothing is resolved anew.
ReferencedConcept/ReferencedMapping) hold the same versioned object. None meansunattributed._get_resolved_system_versions/_get_resolved_valueset_versions. They're exposed asCollectionReference.get_evaluated_repo_versions. A resource-versioned reference's members are judged against the versions of its repository that hold them, so they get their real class too; the expansion still gets theresource_versioned_referencesreason.release. If only HEAD holds it,head. If an unreleased named version holds it (e.g./v1-draft/),unreleased, which makes the expansion unhealthy (unreleased_versions): references can't resolve to an unreleased version yet. A HEAD carrying the legacyreleasedflag isn't a release.interimwhen no active release and not HEAD holds it. Only releases the collection's owner can see count: publicly viewable ones (their HEAD public too) and the owner's own. Health is stored, not computed per viewer, so a class doesn't reveal a release a viewer can't see.mismatchotherwise.mismatch, counted apart ashead_concept/head_mapping(decision 2). The same sub-counts sit onambiguous_members, for a HEAD object that references judge differently.ambiguous.Reasons
inconsistent_resolution: a repository's unversioned references took their members from versions that have no one version in common, judged from which resolved versions hold each reference's members. A repository merely recorded at two versions doesn't trigger it.duplicate_repo_versions: a repository is recorded at two versions and at least one came from an unversioned reference. Only explicit versions meansmultiple_named_versions, which is information, not a reason (decision 1).resource_versioned_references.unresolved_references.system_version_unresolved, counted apart from the otherunresolved_repo_versionsentries.value_set_without_expansion: a value-set reference resolved only to collection versions with no default expansion. Its members get no judgement from it, since there's nothing to judge them against. An exclude reference against such a value set excludes nothing, so it's counted too. A value set named with its version resolves to the version the expansion recorded, even once that version is retired.unreleased_versions,interim_resource_versions,version_mismatches,ambiguous_membersandunattributed_members.locked_version_deletedcomes with #3001.State:
empty, elseunhealthywhen any reason applies, elsehead_resolved, elsehealthy.Cost
For each resource type it runs a few set-based queries: attribution, containment and "held by a release or HEAD", each with the members as a subquery. Per reference, it does only the cached version resolution.
Every reference that has no namespace of its own gets the collection version's namespace from a single toggle read. Without that, each reference would read the toggle once.
A test checks that the query count is the same for 2 and 6 references.
The "held by a release or HEAD" check runs only for members that none of their references' resolved versions hold, looked up by id in batches of 10,000. A healthy expansion doesn't send it at all.
Production
EXPLAIN(read-only, SM-CON-SET 1.0.1, 140 include references, 4 recorded source versions):collections_referencedconcept/collections_referencedmappingthroughreference_id. No full scan, so OpenConceptLab/ocl_online#586 | Expansions use their locked source versions when references are added, and new collection versions copy HEAD's expansion #968's problem doesn't recur.concepts_sources_source_concept_idx/mappings_sources_source_mapping_idx.concept_idindex. For about 250k mapping members, with every member as a subquery, the planner chose a full parallel scan ofmappings_sources. That's why the check now runs by id, only for unheld members.Judgement calls
evaluated_collection_versions. After a build, unversioned references' repositories are recorded, so this only applies to older expansions (a test covers the build case).resource_versioned_referencescounts exclude references too: pinning is deprecated for both (#2504).Tests
core/collections/tests/tests_health.pycovers:unreleasedhead_mappingcounted apartinconsistent_resolutionapart from a repository recorded at two versionsinterimintomismatchpylint -j0 core/exits 0. The local oclapi2 stack is down, so the tests run in CI only.🤖 Generated with Claude Code