Skip to content

OpenConceptLab/ocl_issues#3008 | preview and convert resource-versioned references (API) - #1033

Open
snyaggarwal wants to merge 6 commits into
masterfrom
issues-3008-convert-resource-versioned-references
Open

snyaggarwal wants to merge 6 commits into
masterfrom
issues-3008-convert-resource-versioned-references

Conversation

@snyaggarwal

@snyaggarwal snyaggarwal commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

The API half of OpenConceptLab/ocl_issues#3008 (epic OpenConceptLab/ocl_issues#2942). Web half: OpenConceptLab/oclweb3#111, the TBv3 dialog that uses these endpoints and needs this PR deployed first. It lets a collection's editors see what converting its resource-versioned references would keep, and convert them in one step. This one is off master, independent of the expansion health stack.

Endpoints (HEAD only, editors only)

POST /<owner>/collections/<collection>/references/conversions/preview/ with {"ids": [...]} (at most 500) or {"ids": "*", "offset": n} (every resource-versioned reference, 500 per page). It changes nothing.

For each reference, the response gives:

  • its members now;
  • for each conversion (repo_versioned and unversioned):
    • the new expression;
    • the repo version it resolves to, and how that was chosen (named, recorded, lock, release, HEAD, latest);
    • the members it would bring in;
    • which members it adds and which it removes;
    • keeps_members: whether those match today's members.
  • creates_lock, on unversioned only: when no lock exists for the repo, adding a version-less reference makes the version it resolved to the collection's lock.

Each member list names at most 25 members, and its _count says how many there are. Everything is evaluated as the requester, as the conversion will be, so an editor never sees members of a source they can't view.

The summary gives repo_versioned_keeps_all and unversioned_keeps_all, so TBv3 can offer a one-step conversion. It also gives total, offset and next_offset for paging through "*".

POST /<owner>/collections/<collection>/references/conversions/ with {"conversions": [{"id": ..., "to": "repo_versioned" | "unversioned"}]} or {"all": "repo_versioned" | "unversioned"}. It runs as a task, so ?async=true works for large collections. Each result is one of:

  • converted, with the new reference's id;
  • already_present: the converted expression was already in the collection, so only the old reference goes;
  • not_converted, with a reason;
  • rolled_back.

The rules, as decided on Nov 23

  • The swap happens on the server, in one transaction. The old references and their members go, then the new ones are added and evaluated as any added reference is. That replaces TBv3's add-then-delete with a hand-made rollback. If any new reference can't be added, nothing changes. Released collection versions keep their references.
  • Repo-versioned picks the version this way: a version the HEAD expansion already records that holds the resource version, so members don't move. Otherwise, the one adding the reference would pick: the lock, then the newest release, then HEAD. That's the same rule as Rebuild every expansion's explicit and evaluated repo version lists ocl_issues#3005. A reference that already names a repo version keeps it.
  • Unversioned resolves as adding it would: under the collection's lock, else the latest release.
  • What's kept from the old reference: its cascade, its include or exclude, and its other options. The resource version is dropped, along with any transform, which would otherwise make resource-versioned references again.
  • Cascades are evaluated in full: a reference with a cascade is compared member set against member set, mappings included.
  • Not handled: references that also name a value set, or that have a filter, are reported as not supported.

Load

  • Shared lookups: the collection, namespace and repo-version resolutions are shared across references. The versions holding each resource version are looked up once per repository, and member URLs come from two queries per page.
  • What stays per reference: each conversion is evaluated the way adding the reference would evaluate it, a query or two each.
  • Page size: "*" previews are capped at 500 references per request.
  • Checkpoint: conversions go through the same write checkpoint as adding references.

Tests

core/collections/tests/tests_reference_conversions.py has 17 tests:

  • the preview of both conversions, under a lock and without one;
  • the recorded version preferred;
  • a reference that isn't resource-versioned;
  • mappings;
  • a cascade;
  • paging "*";
  • converting to each kind, and all;
  • already_present;
  • a failed add rolling everything back;
  • a conversion that can't be made, while the others go ahead;
  • released versions untouched;
  • evaluation as the requester;
  • capped member lists;
  • permissions and input validation.

They pass locally with Redis unreachable, as in CI.

🤖 Generated with Claude Code

…n's resource-versioned references to repo-versioned or unversioned ones

@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 7e49ecf.

What checks out:

  • The swap: it's one transaction, it removes and then adds through the normal paths, and it rolls back fully if any add fails.
  • Scope: HEAD only and editors only, and conversions go through the write checkpoint.
  • Version picking: recorded, then as adding would pick, matching OpenConceptLab/ocl_issues#3005. A named version is kept.
  • Kept options: the cascade and include or exclude are kept, and transform is dropped.
  • Other cases: an expression already present only removes the old reference, and released versions are untouched.
  • Load: lookups are batched per repository, and member URLs come from two queries.

The important finding (inline) is that the preview evaluates converted references with the original creator's access, while the conversion uses the requester's. That can show an editor members of a private source they can't view, and it lets the preview disagree with the result.

…uester; the preview says when unversioned creates a lock and caps member lists with counts
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

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

  1. Evaluated as the requester (important): converted references are now built with the requester as created_by, in both the preview and the conversion. The preview can't show members of a source the editor can't view, and it evaluates exactly as the conversion will. A test previews as an org editor who can't view the source: nothing from it is brought in.
  2. creates_lock (nit): unversioned previews now say whether the conversion would make the resolved version the collection's lock.
  3. Quadratic list (nit): plan() builds the reference list once.
  4. Unbounded member lists (nit): each list now names at most 25 members, with a count. Each conversion also says what it adds and what it removes.

There are two new tests, so 17 in all. They pass locally with Redis unreachable, as in CI, 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 once CI passes. No findings on a3872a1.

All four fixes check out:

  • Requester: converted references are built with the requester as created_by, so the preview and the conversion evaluate with the same access, and an editor sees nothing from a source they can't view. The new test covers that.
  • creates_lock: it's set on unversioned whenever the resolved version isn't already the collection's lock.
  • List building: plan() builds the reference list once.
  • Member lists: each names at most 25 members, with counts. keeps_members, added and removed are computed on the full sets before the lists are capped.

I found nothing else across the PR. The tests also pass with Redis unreachable, so they don't depend on a broker in CI.

Still to do for OpenConceptLab/ocl_issues#3008, outside this PR: the TBv3 dialog, and the KB's "blocked" line for converting to repo-versioned.

@snyaggarwal
snyaggarwal requested a review from paynejd November 23, 2026 09:09
…ly versions the collection's owner can view
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Jon's point on OpenConceptLab/ocl_online#549 is addressed in c6ed52f. When no recorded version holds the resource version, the repo-versioned pick now chooses only among versions the collection's owner can view: public ones and the owner's own. A conversion can no longer pin the collection to another owner's private release. A new test covers it. The local Elasticsearch container is down, so CI is this commit's first test run; pylint is clean.

@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 10b2e9d. An independent defect pass (Codex, high effort), with every finding checked against the code. The owner's-view point from this morning is fixed and not repeated.

Verdict: request changes, for point 1. HEAD-only and editors-only both hold, in the view and in the worker.

Must fix before merge

  1. A pinned reference with no system fails the whole batch. prime() calls self.resolve(reference.system, ...) unguarded (reference_conversions.py ~41). With system=None, resolve_reference_expression reaches canonical_url_to_url_and_version(None), where '|' in None raises TypeError. Both preview() and plan() prime every reference before the unsupported check, so one such reference makes "*" previews and "convert all" fail for the whole collection. Production has collections with legacy references like that: the expression names a concept or mapping version (/orgs/CIEL/sources/CIEL/concepts/1065/5512158/), but system was never filled in, and they hold no members. No toggle covers this endpoint. Master's resolve_expression_system_version guards with if self.system. Suggestion inline.
    With the guard, these fall through to get_unsupported_reason as "not resource-versioned", because is_resource_versioned needs a system. A clearer reason would be "it has no system" (suggestion inline). A reference that names only value sets, which FHIR allows, is already left alone, and that's right: such an include lists no codes to convert. Please add a test that mixes a reference with no system into a "*" preview and an all conversion.

Worth fixing
2. already_present ignores cascade. plan() (~266-270) matches on expression and include only, and build_expression has no cascade in it. If the collection already has the converted reference without the old one's cascade, the old reference is deleted and its cascaded mappings drop out, while the preview said "keeps". Match on cascade too, and key the in-batch dict by (expression, include, cascade).
3. Pinned exclusions. Unpinned, an exclusion removes every version of the concept (__exclude_resources, collections/models.py ~2167-2177). But the preview compares only the exclusion's own matched set (~204-207), so it shows "keeps" for a change that can drop a member. Suggest reporting pinned exclusions as unsupported for now. Suggestion inline.
4. No check between preview and convert. The convert request carries {id, to}, and plan() re-resolves. A release published in between changes the result unseen. Accept an optional expected repo_version per conversion, which the preview already returns. Report not_converted ("changed since the preview") when it differs. TBv3 then sends it back.
5. is_visible should use is_publicly_viewable (~115-122), which also needs a public HEAD. Suggestion inline. It's the same rule as #1025 and #1032.

Minor
6. The unversioned target's repo_version (~206) can name a release the requester can't view, because default resolution has no access check. Treat a target the requester can't view as not possible.
7. The worker doesn't recheck edit access (tasks.py ~222). That matches add_references today. Optional: recheck in both.
8. A version label containing + resolves through unquote_plus to a space, so the reference is saved with no members and reported converted. Optional: in convert(), check that each added reference resolved to the planned version.

self.expansion = collection.expansion
self.namespace = Expansion.get_system_version_namespace(collection.parent_url)
self._holders = {}
self._resolved = {}

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: the per-version cache is_visible uses (apply with the is_visible suggestion).

Suggested change
self._resolved = {}
self._resolved = {}
self._visible = {}

reference.collection = self.collection
if not reference.namespace:
reference.__dict__['resolution_namespace'] = self.namespace
system_version = self.resolve(reference.system, reference.resolution_namespace, reference.version)

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: a reference with no system resolves to nothing instead of raising, as master's resolve_expression_system_version does.

Suggested change
system_version = self.resolve(reference.system, reference.resolution_namespace, reference.version)
system_version = self.resolve(
reference.system, reference.resolution_namespace, reference.version) if reference.system else None


@staticmethod
def get_unsupported_reason(reference):
if not reference.is_resource_versioned:

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: names the reason for a pinned reference with no system, before the resource-versioned check that needs one.

Suggested change
if not reference.is_resource_versioned:
if reference.code and reference.resource_version and not reference.system:
return 'it has no system'
if not reference.is_resource_versioned:

return 'it also names a value set'
if reference.filter:
return 'it has a filter'
return None

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 3: reports a pinned exclusion as unsupported for now (every reference reaching this line is pinned).

Suggested change
return None
if not reference.include:
return 'it is an exclusion'
return None

Comment on lines +115 to +122
def is_visible(self, repo_version):
"""Whether the collection's owner can view it: a public version or the owner's own"""
from core.common.models import BaseModel
if repo_version.public_access in BaseModel.PUBLIC_ACCESS_VALUES:
return True
if self.collection.organization_id:
return repo_version.organization_id == self.collection.organization_id
return repo_version.user_id == self.collection.user_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: uses the API's own view rule, is_publicly_viewable (its HEAD public too), once per version, as it reads the HEAD (needs the _visible line in __init__).

Suggested change
def is_visible(self, repo_version):
"""Whether the collection's owner can view it: a public version or the owner's own"""
from core.common.models import BaseModel
if repo_version.public_access in BaseModel.PUBLIC_ACCESS_VALUES:
return True
if self.collection.organization_id:
return repo_version.organization_id == self.collection.organization_id
return repo_version.user_id == self.collection.user_id
def is_visible(self, repo_version):
"""Whether the collection's owner can view it: a publicly viewable version (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:
if self.collection.organization_id:
owned = repo_version.organization_id == self.collection.organization_id
else:
owned = repo_version.user_id == self.collection.user_id
self._visible[repo_version.id] = owned or repo_version.is_publicly_viewable
return self._visible[repo_version.id]

…system and exclusions, respect cascades and the previewed version, and offer only versions viewable with their HEAD
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Thanks, Jon. Your review's points are addressed in 1cb3c89, except point 8.

  1. A reference with no system (must fix): prime() now resolves only when there's a system, as resolve_expression_system_version does. Such references are reported as "it has no system", ahead of the resource-versioned check. A new test mixes a legacy reference (/orgs/CIEL/sources/CIEL/concepts/1065/5512158/, no system) into a "*" preview and an all conversion: it's reported and left as it is, and the other reference converts.
  2. already_present and cascade:
    • Same cascade: a match on expression, include and cascade is already_present, as before.
    • Different cascade: if the expression is already there with another cascade, the conversion isn't made: "the collection already has it with another cascade". Adding it would be refused, and swapping would drop the cascaded mappings.
    • Within a batch: conversions are keyed by (expression, include), with cascade compared the same way.
  3. Resource-versioned exclusions: reported as "it is an exclusion" for now.
  4. Checking against the preview: each conversion may carry the repo_version the preview returned. When it now resolves elsewhere, the conversion isn't made: "changed since the preview". Swagger documents the field, and TBv3 sends it back (OpenConceptLab/ocl_issues#3008 | Convert resource-versioned references, showing what each conversion keeps oclweb3#111).
  5. is_visible: applied as you suggested: the owner's own, or is_publicly_viewable, once per version.
  6. Unversioned targets: one the requester can't view isn't offered, and the conversion reports "its system does not resolve to a version you can view".
  7. Edit access in the worker: convert_references now rechecks it before converting. add_references is unchanged, to keep this PR to conversions; it can follow separately.
  8. + in version labels: not done. Your read-only check found no source version name with + or %, so I left it out.

New tests:

  • a release under a private HEAD isn't a candidate;
  • the no-system reference, in a preview and in all;
  • an exclusion;
  • the same expression with another cascade;
  • the previewed version checked, both mismatched and matching.

The requester test now expects no unversioned offer. The local Elasticsearch container is down, so CI is the first run of these; pylint is clean on the changed files.

@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. Every point I raised is met.

  • Declining point 8 is fine: no version label uses + or % today. Labels aren't validated, so one could appear later; that can be its own ticket if it ever matters.

One new blocker: a queued conversion's result is stored as Python text, not JSON (suggestion inline).

  • Why: convert_references is a plain task. AsyncTask.on_success stores json.dumps(retval), then after_return overwrites it with str(retval) (core/tasks/models.py:174). result_all can't parse that.
  • The effect: for any conversion that comes back queued (202), /tasks/<id>/ hands TBv3 a string, and oclweb3#111 can't read the outcome. add_references has the same problem today. QueueOnce tasks don't, because celery_once's after_return doesn't call super.
  • The fix: the suggestion makes this task a QueueOnceCustomTask, as export_source is. perform_task already turns a duplicate into a 409.
  • The root cause, Task.after_return overwriting every plain task's JSON, deserves its own ticket: fixing it globally changes what add_references and the importers store.

Smaller:

  • Preview cost: the preview runs has_view_access(requester) once per reference. For an org-private target, that's a membership query each time, up to 500 a page. Cache it per target, as _visible does.
  • HEAD labels (optional, with oclweb3#111): an unversioned conversion into a source with no release resolves to HEAD. The dialog labels it "Follows HEAD" when chosen_by is HEAD, but not under a HEAD lock. A follows_head flag from version.is_head on each conversion would let TBv3 label it the same way in both cases. It stays the default choice, since unversioned comes first.

Comment thread core/common/tasks.py Outdated
Comment on lines +210 to +211
@app.task(bind=True)
def convert_references(self, user_id, collection_id, conversions):

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.

Stores the result as JSON, so a queued conversion's caller can read it from /tasks/<id>/.

Suggested change
@app.task(bind=True)
def convert_references(self, user_id, collection_id, conversions):
# QueueOnce, as export_source: its after_return replaces AsyncTask's, which stores a result as str(), so the
# task's record keeps this one as JSON for a queued conversion's caller. The same request twice at once gets 409
@app.task(base=QueueOnceCustomTask, bind=True)
def convert_references(self, user_id, collection_id, conversions):

…ed as JSON, the requester's view is checked once per version, and conversions say when they follow HEAD
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Thanks, Jon. All three points from your Nov 24 review are addressed in 12fa6a9.

  1. A queued conversion's result is stored as JSON (the blocker): convert_references is now a QueueOnceCustomTask, as you suggested and as export_source is. celery_once's after_return replaces AsyncTask's, so the JSON that on_success stores is no longer overwritten with str(), and /tasks/<id>/ returns it. The same request sent twice at once gets 409 through perform_task. A new test runs the worker's on_success and after_return hooks on a task record, with the once-lock's backend mocked since CI has no broker. It checks that result_all reads back as the conversion's results. Task.after_return itself is unchanged, as you said; fixing it globally is its own ticket.
  2. The preview's view check: has_view_access(requester) now runs once per target version (can_requester_view, cached as _visible is), not once per reference. A test checks that each version is asked about only once.
  3. HEAD labels: each conversion now carries follows_head, read from version.is_head, so TBv3 can label it the same way whether it names HEAD or resolves to it under a HEAD lock. chosen_by is unchanged. A test covers a source with no release, where both conversions follow HEAD, and the main fixture, where neither does.

Pylint is clean on the changed files. The local Elasticsearch container is down, so CI is the first run of the new tests. OpenConceptLab/oclweb3#111 now reads follows_head.

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