Repository navigation
OpenConceptLab/ocl_issues#3005 | rebuild_expansion_version_lists rebuilds expansions' explicit and evaluated version lists, dry run by default - #1030
Conversation
…ilds expansions' explicit and evaluated version lists from their references and members, dry run by default
snyaggarwal
left a comment
There was a problem hiding this comment.
Review of 9871da6: three important findings and four nits. The rule and the report do what the ticket asks. Fixes follow in this PR.
| def note(self, reference, **kwargs): | ||
| self.notes.append({'reference': reference.id, 'expression': reference.expression, **kwargs}) | ||
|
|
||
| def keep(self, reference, relations, repo_uri, reason): |
There was a problem hiding this comment.
Important: keep() puts old explicit versions back beside rebuilt ones. A reference with no members, or with members that no single version holds, puts every recorded version of its repo back into the list it was in, even when other references of that repo were rebuilt. On old expansions everything is explicit. So with explicit=[v1, v2], a version-less reference holding v1 and another that found nothing end with v1 in both lists and v2 left in explicit. The kept reference's read then sees only the evaluated version. This affects most old expansions, and it skews in_both and the unchanged counts.
Fix: keep a no-member reference's versions only when nothing else recorded that repo. For a reference that no single version holds, record the recorded versions that hold any of its members, in the list that reference reads.
| 'after': after, | ||
| } | ||
|
|
||
| def apply(self): |
There was a problem hiding this comment.
Important: concurrent reference adds can be overwritten by --apply. Nothing that adds references locks the expansion row, so select_for_update in the command doesn't block them. A lock committed between build() and apply() is erased by .set(). The member check compares two reads taken a few statements apart, so it can't detect that.
Fix: at apply time, re-read the four lists and the member summary and compare them with what build() saw; raise and roll back if either differs.
|
|
||
| def build(self): | ||
| versionless = {} | ||
| for reference in self.expansion.collection_version.references.order_by('id'): |
There was a problem hiding this comment.
Important: N+1 queries per reference. Each reference costs several unshared queries:
resolution_namespacefetches its collection and reads a toggle;get_head()runs for each version-less reference (line 115);- with a
system-versionparameter,can_compute_against_system_versionresolves the system again and loads the default expansion's locks for each reference.
A 20,000-reference collection version costs about 60,000 queries, and --all repeats that for every version. Fix: set reference.collection to the collection version, prime the namespace once (as the health classifier does), and cache the head by version id.
| if not total: | ||
| if recorded: | ||
| self.keep(reference, relations, repo_uri, 'it has no members') | ||
| else: |
There was a problem hiding this comment.
Nit (optional): a value-set reference with no members silently gains a lock. When nothing is recorded for its value set, the version resolved now goes into evaluated with no note, so gains_lock lists it without saying why. Fix: add a note with chosen_by: resolved.
| with transaction.atomic(): | ||
| members = self.get_member_summary() | ||
| for relation in self.RELATIONS: | ||
| getattr(self.expansion, relation).set(list(self.after[relation])) |
There was a problem hiding this comment.
Nit (optional): applied lists don't mark expansion health stale. This PR is off master, where mark_health_out_of_date doesn't exist yet. Once #1026 is on master, an --apply run changes lists that health reads and leaves stored health marked current. Whichever merges second should call it after the lists are written.
| for key in ('gains_lock', 'loses_lock', 'in_both'): | ||
| if report[key]: | ||
| self.totals[f'with_{key}'] += 1 | ||
| kept = [note for note in report['references'] if 'reason' in note] |
There was a problem hiding this comment.
Nit (optional): with_references_kept_as_recorded also counts unresolved references, which keep nothing (kept=[]). Fix: count only notes with a non-empty kept, and count unresolved references in a separate total.
| from core.sources.tests.factories import OrganizationSourceFactory | ||
|
|
||
|
|
||
| class ExpansionVersionListsTest(OCLTestCase): |
There was a problem hiding this comment.
Nit (optional): some paths have no test:
- the
system-versionparameter path; - mapping members;
- a value set falling back to a release or HEAD;
- the command's failure line.
…ded no longer puts back versions others rebuilt; apply writes nothing if the expansion changed since the build; queries don't grow with references
|
The review points are addressed in d1f1c57, except the health one. The description is updated.
|
snyaggarwal
left a comment
There was a problem hiding this comment.
Verdict: not ready to merge yet. One important finding and three nits on d1f1c57.
All seven points from the first review are resolved, except the health call, which waits for whichever of this PR and #1026 merges second:
- kept versions no longer sit beside rebuilt ones;
--applywrites nothing if the expansion changed after the build read it;- the system side's query count no longer grows with references;
- the value-set note, the totals and the four missing tests are in.
The important finding: the new fallback check is keyed by repo rather than by the list a reference reads. On expansions built with locking, that can drop an evaluated lock (inline). It's a small fix, and with it this is ready, pending the ticket's pre-production steps: the FHIR parity subset, the reviewed production dry run with Jon's OK, the filed copies and the release note.
| for relation, versions in self.after.items() for version in versions.values()} | ||
| kept_repos = set() | ||
| for reference, relations, repo_uri, reason in self.fallbacks: | ||
| key = (relations[0].split('_')[1], repo_uri) |
There was a problem hiding this comment.
Important: the fallback check can drop a version-less reference's lock. A fallback is skipped when any list records the repo. But a version-less reference reads the evaluated list, and a reference naming a version fills only explicit.
Example: an expansion built with locking has evaluated=[v1] and explicit=[v2], a filter reference that matches nothing now, and a reference naming v2. The rebuild records explicit v2, skips the filter reference's fallback, and drops evaluated v1 (loses_lock). After --apply, later version-less adds to that HEAD resolve to the latest release instead of v1.
Fix: key recorded_repos and the check by the reference's own read list (relations[0]) and repo, so a fallback is skipped only when that list already holds the repo.
| self.record(EVALUATED_COLLECTIONS, version) | ||
| self.note(reference, recorded=version.uri, chosen_by='resolved', reason='it has no members') | ||
| return | ||
| for candidates, chosen_by in ((recorded, 'recorded'), (self.releases_then_head(version), 'release')): |
There was a problem hiding this comment.
Nit (optional): value-set references still cost queries per reference. The tuple runs releases_then_head(version) before the loop, even when a recorded version holds the members. valueset_holds also reads candidate.expansion with a fresh query for each reference and candidate. Making the release candidates lazy and caching the default expansion id by version id would bring this in line with the system side.
| pending = self.pick_holders(pending, include, parent_id, totals, candidates, chosen_by) | ||
| for reference in pending: | ||
| self.record_partial_holders( | ||
| reference, [version for version in recorded if held_by_recorded[(reference.id, version.id)]], |
There was a problem hiding this comment.
Nit (optional): partial holders can include versions that add nothing. Every recorded version holding any member goes into evaluated. If c1 is in v1 and v2 and c2 only in v3, all three are recorded where v1 and v3 cover everything. A covering set (newest first, adding a version only for members not yet covered) would read more truthfully.
| kept_repos = set() | ||
| for reference, relations, repo_uri, reason in self.fallbacks: | ||
| key = (relations[0].split('_')[1], repo_uri) | ||
| if key in recorded_repos and key not in kept_repos: |
There was a problem hiding this comment.
Nit (optional): key not in kept_repos can never change the outcome. Keys only enter kept_repos when they aren't in recorded_repos, so the condition reduces to key in recorded_repos.
…list its reference reads holds the repo; value-set lookups are lazy and cached; split members record a covering set
|
All four points from the second review are fixed in the latest commit. The description is updated.
31 tests pass locally, and pylint is clean on the changed files. |
snyaggarwal
left a comment
There was a problem hiding this comment.
Verdict: not ready to merge yet. One important finding and one nit on 0e37f4b.
The second review's four fixes check out:
- a fallback is now skipped only when the list its reference reads holds the repo;
- value-set releases are looked up lazily, with HEAD and expansion lookups cached;
- split members record a covering set;
- the dead check is gone.
The important finding is a lock moving silently. The recorded candidates are sorted newest first across both lists, so a version another reference names can replace a version-less reference's lock, and no report flag shows it (inline). Once that's fixed, I don't see anything else blocking, apart from the ticket's pre-production steps.
| self.keep(reference, (EVALUATED_SOURCES, EXPLICIT_SOURCES), repo_uri, 'it has no members') | ||
| else: | ||
| pending.append(reference) | ||
| recorded = self.recorded_versions_of((EVALUATED_SOURCES, EXPLICIT_SOURCES), repo_uri) |
There was a problem hiding this comment.
Important: a lock can silently move to a newer version that another reference names. The recorded candidates mix evaluated and explicit versions and sort them newest first. So when both hold a version-less reference's members, as unchanged concepts usually do, an explicit v2 beats the evaluated lock v1. gains_lock and loses_lock only compare which repos are locked, so the report doesn't show it.
Example: a HEAD built with locking has evaluated=[v1], explicit=[v2], a version-less reference whose concept is in both, and a reference naming v2. The rebuild records evaluated v2 and drops v1 with no flag. After --apply, later version-less adds resolve to v2 instead of the v1 the owner locked.
Fix: try the recorded versions of the list the reference reads first (evaluated, newest first), then the other list, then releases. Do the same for value sets (line 315). Add a changes_lock entry when a repo's evaluated versions differ before and after.
| reference, self.get_covering_versions(recorded, { | ||
| holder.id: self.get_held_by_valueset(holder, reference) for holder in recorded}), relations, repo_uri) | ||
|
|
||
| def valueset_holds(self, valueset_version, reference, total): |
There was a problem hiding this comment.
Nit (optional): valueset_holds now loads every member id per candidate, where it used to run a COUNT. A large value-set reference pulls its whole member list once per candidate version. Keeping a count here and fetching ids only for the covering set would avoid that.
…ock over a newer version another names, and a moved lock is reported; value set holder checks count
|
Both points from the third review are fixed in the latest commit. The description is updated.
33 tests pass locally, and pylint is clean on the changed files. |
snyaggarwal
left a comment
There was a problem hiding this comment.
Verdict: ready to merge from this review, once CI passes. One optional nit on ff05194.
Both third-review fixes check out:
- Locks: a version-less reference tries the recorded versions of the list it reads first, so an existing lock beats a newer version another reference names. That applies to value sets too.
changes_lock: it reports a lock that does move, and it's in the totals and on each line.- Value sets:
valueset_holdscounts again, and ids are fetched only for the covering set.
I went over the whole PR again: the rule's branches, the fallbacks, the --apply checks against concurrent changes, the query sharing, the report and the command. I found nothing else.
Still open, and not part of the code:
- Health: the call to mark expansion health out of date goes in whichever of this PR and #1026 merges second.
- Before the production run, per the ticket: the FHIR parity subset, the reviewed production dry run with Jon's OK, the filed before-and-after copies, and the release note for self-hosted installs.
|
|
||
| @staticmethod | ||
| def get_covering_versions(versions, held): | ||
| """Newest first, each version holding a member none before it holds""" |
There was a problem hiding this comment.
Nit (optional): this docstring and the printed rule still say "newest first" for the covering set. The recorded versions now come in the order the reference reads them: its own list first, then the other, each newest first. Saying "in the order given" here, and "the reference's own list first" in the rule's sentence about split members, would keep the dry-run text accurate.
…ing say split members take the reference's own list first
|
The wording nit is fixed in the latest commit. The covering-set docstring now says "in the order given". The printed rule says split members take the recorded versions from the reference's own list first. The 33 tests pass locally, and pylint is clean. |
…collection's owner can view; --skip-released, and the report counts released apart and members whose reported release changes
|
Jon's three points on OpenConceptLab/ocl_online#549 are addressed in 38cc33b.
There are new tests for the visibility filter, the owner's own private release, the reported-release count, The local Elasticsearch container is down, so these ran only through pylint (clean) locally. CI is the first full run. |
paynejd
left a comment
There was a problem hiding this comment.
Review at fdbe701. An independent defect pass (Codex, high effort), with every finding checked against the code. This morning's three points are fixed and not repeated.
Verdict: approve. Please do points 1-4 before the production run. The core holds. --apply only .set()s the four version-list relations, inside the row lock, and re-checks the member count and id sum, so members can't change. Dry run and apply share build() and to_report(). reported_release_changes follows $expand's order exactly. --skip-released filters at selection.
Before the production run
- Private release in the resource-version fallback. The owner's-view filter covers
releases_then_head, but not the second pick inversion_lists.py~221-227. That pick runs over every active version of the source, with no visibility check. The member-less value-set path (~344) has the same gap. Suggestion inline for the first. For the second, record the resolved version only if it's visible, elsekeep(). _headscache key. It's keyed byversion.idonly (~58-61), but it caches both Source and Collection versions, which live in separate tables. A matching id returns the wrong type. Suggestion inline: key by (type, id).- A canonical system that no longer resolves drops its recorded version. Line ~193 resolves with today's rules. When nothing resolves, or it resolves to a repo that holds none of the reference's members, the version the members came from drops out as unused. Instead,
keep()the recorded versions of the repos the members belong to, and give that case its own note and total in the dry run. - A second run can change the lists again. One case: R1's member is in v1 and v2, and R2's only in v2. The first run gives evaluated {v1, v2}. The second sorts that newest first, and both references pick v2. FHIR's answer is the same both times, but the lock list moves. Iterate each versionless group's picks until nothing changes, and add the case to the idempotence test.
Smaller
5. Under --skip-released, re-check released inside the transaction: a version published during the run would otherwise be rewritten. Suggestion inline.
6. Open the --output file before the loop, so a bad path fails before anything is written. Suggestion inline.
7. The reported_release_changes docstring overstates its match with $validate-code. That only differs for a code system whose releases carry different canonical URLs. Suggested wording inline.
8. keep_fallbacks can leave a version in both lists when only one kind of reference uses it. It's harmless for FHIR and adds, so report it or leave it.
9. The release note for self-hosted installs is still to write, as the checklist says.
For the dry-run report: please make with_gains_lock easy to find. Gaining a lock changes what a HEAD collection's next unversioned add resolves to, and Jon decides that with the numbers in front of him.
| locked = self.recorded_versions_of((EVALUATED_SOURCES,), repo_uri) | ||
| picked = CollectionReference.pick_repo_version_with_resource_version( | ||
| [holder for holder in holders if holder.id in recorded_ids], locked | ||
| ) or CollectionReference.pick_repo_version_with_resource_version(holders, locked) |
There was a problem hiding this comment.
Point 1: filters the second pick to versions the collection's owner can view, as releases_then_head does.
| ) or CollectionReference.pick_repo_version_with_resource_version(holders, locked) | |
| ) or CollectionReference.pick_repo_version_with_resource_version( | |
| [holder for holder in holders if self.is_visible(holder)], locked) |
| if version.id not in self._heads: | ||
| self._heads[version.id] = version.get_head() | ||
| return self._heads[version.id] |
There was a problem hiding this comment.
Point 2: keys the HEAD cache by model and id, since Source and Collection ids come from separate tables.
| if version.id not in self._heads: | |
| self._heads[version.id] = version.get_head() | |
| return self._heads[version.id] | |
| key = (type(version).__name__, version.id) | |
| if key not in self._heads: | |
| self._heads[key] = version.get_head() | |
| return self._heads[key] |
| """How many concept members FHIR $expand and validate-code would report from another release after the | ||
| rebuild. They report the live release holding the member: explicit pin first, then evaluated, then the newest | ||
| (by id). Judged as the collection's owner is shown, as a viewer's view can only narrow it""" |
There was a problem hiding this comment.
Point 7: says where $validate-code can differ instead of claiming it matches.
| """How many concept members FHIR $expand and validate-code would report from another release after the | |
| rebuild. They report the live release holding the member: explicit pin first, then evaluated, then the newest | |
| (by id). Judged as the collection's owner is shown, as a viewer's view can only narrow it""" | |
| """How many concept members FHIR $expand would report from another release after the rebuild. It reports the | |
| live release holding the member: explicit pin first, then evaluated, then the newest (by id). $validate-code | |
| picks the same way among the releases the coding's system names, so it can differ only for a code system whose | |
| releases carry canonical URLs of their own. Judged as the collection's owner is shown, as a viewer's view can | |
| only narrow it""" |
| self.totals = Counter() | ||
| mode = 'APPLY' if options['apply'] else 'DRY RUN' | ||
| self.stdout.write(f'{mode}. Rule: {RULE}') | ||
| for expansion_id in self.get_expansion_ids(): |
There was a problem hiding this comment.
Point 6: opens the output file before the loop, so a bad path fails before any expansion is written.
| for expansion_id in self.get_expansion_ids(): | |
| if options['output']: | |
| # a bad path fails here, before anything is written | |
| open(options['output'], 'a', encoding='utf-8').close() | |
| for expansion_id in self.get_expansion_ids(): |
| with transaction.atomic(): | ||
| # a dry run takes no lock | ||
| expansions = Expansion.objects.select_for_update() if self.options['apply'] else Expansion.objects | ||
| expansion = expansions.get(id=expansion_id) |
There was a problem hiding this comment.
Point 5: re-checks released inside the transaction, so a version released after selection is skipped, not rewritten.
| expansion = expansions.get(id=expansion_id) | |
| expansion = expansions.get(id=expansion_id) | |
| if self.options['skip_released'] and expansion.collection_version.released: | |
| # released after it was selected | |
| self.totals['skipped_released'] += 1 | |
| return |
…tem no longer resolves, offers only viewable versions, settles its picks, and rechecks released versions
|
Thanks, Jon. Points 1-7 are addressed in 232592d. Points 8 and 9 are below, and the dry-run summary now leads with the lock count. Before the production run
Smaller
Not done here: the product calls stay with Jon. That includes whether released collection versions are included in the production run; There are new tests for points 1, 3, 4, 5 and 6, and for the gains-lock line. The local Elasticsearch container is down, so CI is the first run of these. |
paynejd
left a comment
There was a problem hiding this comment.
Thanks, Sunny. Points 1 to 3 and 5 to 7 are met, and 8 and 9 are fine as you left them. The gains-lock line is easy to find. My approval stands.
Point 4, before the production --apply: a second run can still move a lock list. settle works within one group, and groups split includes from excludes (core/collections/version_lists.py:225). A second run, though, reads every evaluated version of the repository. Example, starting from the legacy shape (explicit {v1}):
- include R1's member is in v1 and v3; exclude R2's member is only in v3;
- run 1 records R1 at v1 and R2 at v3, so evaluated is {v1, v3};
- run 2 sees [v3, v1] and moves R1 to v3, so evaluated becomes {v3}.
record_partial_holders can do the same. Members never change and FHIR reports the same release, so only the lock list churns.
The fix: settle per repository across both groups, with the repository's already-recorded evaluated versions as candidates, and record only after settling. Add the include/exclude case to the R1/R2 test. If you'd rather leave it, check it on staging: after an --apply, a second dry run should report 0 changed, and any change it does report is this.
Smaller:
- Stale dry-run notes: a reference that
settlemoved still names its first pick. In your R1/R2 test, R1's note says v1 but v2 is recorded. Add a note with the new version for each reference that moved. - The printed rule: the rule printed at the start of each run doesn't mention settling.
with_gains_lock_headcounts every HEAD expansion, non-default ones included, and their locks don't affect the next add. "of those" also assumes HEAD is unreleased.report['is_head'] and report['is_default']fixes both; each JSON line carries both fields, so the dry-run numbers can be filtered meanwhile.--skip-releasedreads the collection version without a lock, so a release committed while that one expansion rebuilds is still rewritten.select_for_update(of=('self', 'collection_version'))on the apply path closes it, if you want.- A stale comment: the comment at
rebuild_expansion_version_lists.py:103still mentions validate-code.
The release note (point 9): please publish it with the release that ships this. The text is right.
…es settle together across includes and excludes, moved picks are noted, and apply locks the collection version
|
Thanks, Jon. Your round 2 is addressed in ce5fb9d. Point 4, a second run moving a lock list:
Smaller
Release note: it'll go out with the release that ships this, with the text as you approved it. The local Elasticsearch container is still down, so CI on ce5fb9d is the first test run. |
For OpenConceptLab/ocl_issues#3005 (epic OpenConceptLab/ocl_issues#2942). Expansions built before version locking list every repo version they used as explicit: the old resolved list was renamed to explicit and never split. This PR adds a command that rebuilds each expansion's explicit and evaluated lists from its references and members. It's a dry run unless
--applyis given, and it never changes a member.--start-after-idand--limitlet a long--allrun resume.The rule
The command prints this rule at the start of every run.
Named version: a reference that names a repo version records it as explicit.
Resource-versioned reference: records as explicit the version that holds its resource version. That's a version the expansion already records if one holds it, otherwise the one adding the reference would pick.
Version-less reference: records as evaluated the version its members came from. When the members sit in several versions of the repo, the choice is, in order:
Only members from the reference's own repo count. For include references, only those still in the expansion count. Exclude references are judged by what they matched.
A version both kinds use goes in both lists. That's what adding references does today, and the reads need it: version-less references read the evaluated list, resource-versioned ones read the explicit list.
No single version holds all its members: the reference records the recorded versions that between them hold them, in the list it reads. It goes newest first and adds a version only for members the newer ones lack.
Nothing to judge by: a reference with no members, or one whose members no recorded version holds, keeps whatever the expansion records for its repo. It does that only when the list it reads doesn't already hold the repo, so it can't put back a version the others moved, and a reference naming a version can't make it drop a lock. The report says why either way.
Unused versions: a recorded version that no reference uses is dropped.
Value sets: the same rule applies. A versioned value set is explicit. A version-less one records the version, recorded first, whose default expansion holds the reference's members.
system-versionparameter: when an expansion's parameter applies to a reference, the version it names is recorded, as adding the reference does.The report
gains_lock,loses_lockandchanges_lock: repos that gain, lose or change an evaluated version, so later adds of version-less references would resolve differently;in_both;Safety
--applywrites only the four version lists, and only for changed expansions. Each write runs in its own transaction with the expansion row locked.--applychecks the lists, references and members against what the rebuild read. If anything changed in between, it writes nothing for that expansion and reports it as a failure.Tests
core/collections/tests/tests_version_lists.pyhas 33 tests:--apply;--applywrites nothing when the expansion changed after the rebuild read it;They pass locally, and pylint is clean on the new files.
Before the production run (per the ticket)
This PR is independent of the expansion health stack (#1025, #1026, #1029). The health backfill runs after this has run on production.
🤖 Generated with Claude Code