Skip to content

OpenConceptLab/ocl_issues#3005 | rebuild_expansion_version_lists rebuilds expansions' explicit and evaluated version lists, dry run by default - #1030

Open
snyaggarwal wants to merge 9 commits into
masterfrom
ocl_issues-3005-rebuild-expansion-version-lists
Open

snyaggarwal wants to merge 9 commits into
masterfrom
ocl_issues-3005-rebuild-expansion-version-lists

Conversation

@snyaggarwal

@snyaggarwal snyaggarwal commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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 --apply is given, and it never changes a member.

python manage.py rebuild_expansion_version_lists --all --output report.jsonl           # dry run
python manage.py rebuild_expansion_version_lists --all --apply --output applied.jsonl
python manage.py rebuild_expansion_version_lists <expansion or collection version URI> ...

--start-after-id and --limit let a long --all run 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:

    1. a version the expansion already records that holds all of them: first those in the list the reference reads (so an existing lock wins), then the others, each newest first;
    2. the newest live release holding all of them;
    3. HEAD.

    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-version parameter: when an expansion's parameter applies to a reference, the version it names is recorded, as adding the reference does.

The report

  • One JSON line per changed expansion, with:
    • its lists before and after, so the file is the before-and-after copy for the production run;
    • what each list gains and loses;
    • gains_lock, loses_lock and changes_lock: repos that gain, lose or change an evaluated version, so later adds of version-less references would resolve differently;
    • in_both;
    • notes on references: which version each picked when several held its members, and which kept what was recorded;
    • member counts and id sums.
  • Failures are reported as lines of their own.
  • Totals come at the end.

Safety

  • Members: --apply writes only the four version lists, and only for changed expansions. Each write runs in its own transaction with the expansion row locked.
  • Concurrent edits: reference adds don't take that lock, so before writing, --apply checks 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.
  • Dry run: takes no lock and writes nothing.
  • Queries: on the system side, the query count doesn't grow with the number of references. References share one collection and namespace lookup, and lookups of HEAD, releases and value set expansions are cached. Releases are looked up only when no recorded version holds the members.

Tests

core/collections/tests/tests_version_lists.py has 33 tests:

  • each branch of the rule;
  • members unchanged after --apply;
  • a second rebuild changes nothing;
  • the dry run leaves the lists alone;
  • --apply writes nothing when the expansion changed after the rebuild read it;
  • the query count stays the same as references are added;
  • the command's arguments.

They pass locally, and pylint is clean on the new files.

Before the production run (per the ticket)

  • A FHIR parity subset passes.
  • The production dry run is reviewed, and Jon gives his OK.
  • The before-and-after copies are filed.
  • A release note tells self-hosted installs to run the command after upgrading.

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

…ilds expansions' explicit and evaluated version lists from their references and members, dry run by default

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/collections/version_lists.py Outdated

def build(self):
versionless = {}
for reference in self.expansion.collection_version.references.order_by('id'):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: N+1 queries per reference. Each reference costs several unshared queries:

  • resolution_namespace fetches its collection and reads a toggle;
  • get_head() runs for each version-less reference (line 115);
  • with a system-version parameter, can_compute_against_system_version resolves 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): some paths have no test:

  • the system-version parameter 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
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

The review points are addressed in d1f1c57, except the health one. The description is updated.

  1. Kept versions (important): a reference with no members, or whose members no recorded version holds, now keeps what's recorded only if no other reference records its repo. That decision is made after the others, so it can't put back a version they moved. A reference whose members no single version holds now records each recorded version holding some of them, in the list it reads.
  2. Concurrent adds (important): --apply now checks the lists, references and members against what the rebuild read before writing anything. If any of them changed, it writes nothing for that expansion and reports a failure.
  3. Query count (important): references share one collection and namespace lookup. The system-version parameter check now uses the cached resolution, and HEAD lookups are cached by version. A test checks that the query count is the same for 2 and 6 references.
  4. Value set with no members (nit): it now gets a note with chosen_by: resolved.
  5. Health (nit): not changed here. mark_health_out_of_date isn't on master yet, so whichever of this PR and OpenConceptLab/ocl_issues#3003 | expansion health stored and kept current (PR 2 of 4, stacked on #1025) #1026 merges second adds the call. Either way, the health backfill runs after this command has run on production.
  6. Totals (nit): with_references_kept_as_recorded now counts only references that kept something. Unresolved references, and references whose members came from several versions, have totals of their own.
  7. Tests (nit): added tests for the system-version parameter, mapping members, a value set falling back to a release, and the command's failure line. That makes 28; they pass locally, and pylint is clean on the changed files.

@snyaggarwal
snyaggarwal requested a review from paynejd November 23, 2026 06:55
@snyaggarwal snyaggarwal self-assigned this Nov 23, 2026

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;
  • --apply writes 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.

Comment thread core/collections/version_lists.py Outdated
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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/collections/version_lists.py Outdated
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')):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/collections/version_lists.py Outdated
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)]],

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/collections/version_lists.py Outdated
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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

All four points from the second review are fixed in the latest commit. The description is updated.

  1. Fallback key (important): a fallback is now skipped only when the list its reference reads already holds the repo. A reference naming a version fills explicit, so it no longer makes a version-less reference with no members drop its evaluated lock. A test covers evaluated=[v1], explicit=[v2] with a reference that has no members and one naming v2: nothing changes.
  2. Value-set queries (nit): releases are looked up only when no recorded version holds the members. Releases, HEAD and each value set version's default expansion are cached for the run. A test checks that two value-set references held by a recorded version look up no releases.
  3. Partial holders (nit): split members now record a covering set. It goes newest first and adds a version only when it holds a member the newer ones don't. A test checks that a version adding nothing is left out.
  4. Dead check (nit): kept_repos is gone.

31 tests pass locally, and pylint is clean on the changed files.

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Both points from the third review are fixed in the latest commit. The description is updated.

  1. Lock moving silently (important): a version-less reference now tries the recorded versions of the list it reads first (evaluated, newest first), then the other list, then releases. The same goes for value sets, so an existing lock beats a newer version another reference names. The report has a new changes_lock entry for a repo whose evaluated versions differ before and after, and it's counted in the totals and flagged on each line. Two tests cover this:
    • an evaluated v1 lock stays when a named v2 also holds the members;
    • a lock that does move is reported in changes_lock.
  2. valueset_holds (nit): it counts again, and member ids are fetched only for the covering set.

33 tests pass locally, and pylint is clean on the changed files.

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_holds counts 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.

Comment thread core/collections/version_lists.py Outdated

@staticmethod
def get_covering_versions(versions, held):
"""Newest first, each version holding a member none before it holds"""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

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
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Jon's three points on OpenConceptLab/ocl_online#549 are addressed in 38cc33b.

  1. Released versions:
    • --skip-released leaves out expansions of released collection versions, whether they come from --all or a URI, so the production run can go either way once that's decided.
    • Each report line now says whether its collection version is released (collection_version_released). It also gives reported_release_changes: how many concept members FHIR $expand and validate-code would report from another release after the rebuild. That uses the same order FHIR uses: explicit pin first, then evaluated, then the newest live release, as the collection's owner is shown.
    • The totals split out expansions_, changed_, with_reported_release_changes_ and members_with_reported_release_change_, each released and unreleased.
  2. Private releases: when the recorded versions don't settle it, the fallback candidates are now only releases, and HEAD, that the collection's owner can view: public ones and the owner's own. Nothing else is listed.
  3. "No version is in both": I've put a line on Rebuild every expansion's explicit and evaluated repo version lists ocl_issues#3005 so the criterion matches.

There are new tests for the visibility filter, the owner's own private release, the reported-release count, --skip-released and the split totals.

The local Elasticsearch container is down, so these ran only through pylint (clean) locally. CI is the first full run.

@paynejd paynejd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Private release in the resource-version fallback. The owner's-view filter covers releases_then_head, but not the second pick in version_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, else keep().
  2. _heads cache key. It's keyed by version.id only (~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).
  3. 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.
  4. 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.

Comment thread core/collections/version_lists.py Outdated
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Point 1: filters the second pick to versions the collection's owner can view, as releases_then_head does.

Suggested change
) 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)

Comment thread core/collections/version_lists.py Outdated
Comment on lines +59 to +61
if version.id not in self._heads:
self._heads[version.id] = version.get_head()
return self._heads[version.id]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Point 2: keys the HEAD cache by model and id, since Source and Collection ids come from separate tables.

Suggested change
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]

Comment thread core/collections/version_lists.py Outdated
Comment on lines +437 to +439
"""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"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Point 7: says where $validate-code can differ instead of claiming it matches.

Suggested change
"""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():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Point 6: opens the output file before the loop, so a bad path fails before any expansion is written.

Suggested change
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Point 5: re-checks released inside the transaction, so a version released after selection is skipped, not rewritten.

Suggested change
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
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

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

  1. Private release in the fallbacks:

    • Resource-version fallback: the second pick now runs only over versions the collection's owner can view, as you suggested.
    • Member-less value set: it records the resolved version only if the owner can view it; otherwise it keeps what's recorded.

    Tests cover both with another owner's private versions.

  2. _heads cache: it's now keyed by (type, id), as suggested.

  3. A system that no longer resolves:

    • The fix: when a reference's system doesn't resolve today, or resolves to a repository that holds none of its members, the recorded versions of the repositories its members belong to are kept, in the list the reference reads. They're no longer dropped as unused. The repositories come from two queries per expansion, for all references at once.
    • Notes and totals: each case gets its own note: "its system does not resolve", or "its system resolves to a repository that holds none of its members". The second has its own total, with_references_resolving_elsewhere, next to with_unresolved_references.
    • Your example: this should cover expansion 26353's w3c-provenance-activity-type/4.0.1, which now shows as kept rather than removed. It's worth checking in the production dry run.
  4. Picks that change on a second run: each version-less group's picks now settle. Every reference moves to the newest picked version that holds all its members, until nothing changes. The R1/R2 case is a test: both land on v2, and a second rebuild changes nothing.

Smaller
5. --skip-released: released is rechecked inside the transaction, so a version released after selection counts as skipped_released and isn't rewritten.
6. --output: the file is opened before the loop, so a bad path fails before anything is written. A test covers it with --apply.
7. The reported_release_changes docstring: it uses your wording.
8. A version in both lists from keep_fallbacks: left as it is. As you say, it's harmless for FHIR and for adds, and the report already lists every such version under in_both, so the dry run shows them.
9. Release note: not code, so it's yours or mine to publish. Here's a draft:

After upgrading, rebuild expansions' version lists. Expansions built before version locking list every repo version they used as explicit. Run python manage.py rebuild_expansion_version_lists --all --output report.jsonl as a dry run and review the report, especially gains_lock. Then run it again with --apply. It changes only each expansion's explicit and evaluated version lists, never its members. Add --skip-released to leave released collection versions as they are.

with_gains_lock now has its own line after the totals: "Gaining a lock: N expansion(s), M of them unreleased collection versions, K of those HEAD". The JSON line for each expansion now carries is_head. The totals also split with_gains_lock_released and with_gains_lock_unreleased.

Not done here: the product calls stay with Jon. That includes whether released collection versions are included in the production run; --skip-released handles either answer.

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. pylint -j0 core/ is clean apart from the two existing tests_access_control.py hits.

@paynejd paynejd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 settle moved 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_head counts 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-released reads 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:103 still 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
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Thanks, Jon. Your round 2 is addressed in ce5fb9d.

Point 4, a second run moving a lock list:

  • What changed: version-less references now settle per repository, includes and excludes together. Each group still makes its first picks as before, but nothing is recorded until the repository's groups have settled.
  • Each round:
    • A whole holder moves to the newest version holding all its members. It picks from the versions now picked for the repository plus its already-recorded evaluated versions.
    • A partial holder's covering is recomputed over those versions, evaluated first and then the repository's explicit ones, the way a second run reads them.
  • Stopping: rounds repeat until nothing moves, capped at 10, and only then is anything recorded.
  • Tests:
    • your case is a new test: include R1 in v1 and v3, exclude R2 only in v3, legacy explicit {v1}. Both land on v3, and a second rebuild after --apply changes nothing;
    • the R1/R2 test still asserts the same.

Smaller

  • Moved references' notes: a reference that settling moved now gets a note with the version it ended on, recorded, beside its first pick, settled_from, with the reason "settled with the other references of its repository". The R1/R2 test checks R1's note: v2, moved from v1.
  • The printed rule: it now describes settling.
  • with_gains_lock_head: it now counts report['is_head'] and report['is_default']. The line reads "Gaining a lock: N expansion(s): X of released and Y of unreleased collection versions; Z of them a HEAD's default expansion, whose next add resolves by it", so it no longer assumes HEAD is unreleased.
  • --skip-released: the apply path now locks the expansion and its collection version with select_for_update(of=('self', 'collection_version')). A release committed meanwhile waits, and that expansion is then skipped.
  • The stale comment: it now mentions only $expand.

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. pylint -j0 core/ is clean apart from the two existing tests_access_control.py hits.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants