Skip to content

OpenConceptLab/ocl_issues#3003 | expansion health in the API (PR 3 of 4, stacked on #1026) - #1029

Open
snyaggarwal wants to merge 8 commits into
issues-3003-expansion-health-storagefrom
issues-3003-expansion-health-api
Open

snyaggarwal wants to merge 8 commits into
issues-3003-expansion-health-storagefrom
issues-3003-expansion-health-api

Conversation

@snyaggarwal

@snyaggarwal snyaggarwal commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR 3 of 4 for OpenConceptLab/ocl_issues#3003, stacked on #1026, which is itself stacked on #1025. Its base is #1026's branch, so this diff shows only PR 3. Merge in order and retarget each PR to master as the one below it merges.

It exposes the stored health. It adds no writes and no new computation, apart from ?includeHealth=true, which classifies one page on request.

Expansions

  • Expansion list and detail return health (the stored summary) and health_is_current, read-only.
    • health_is_current is true when current, false when a recompute is queued, and null when nothing is queued.
    • Visibility: anyone who can view the collection version sees them, as set for the badge on Nov 3.

Collection versions (for TBv3's versions table, OpenConceptLab/ocl_issues#3004)

  • The versions list returns each version's expansion_health: {"state": ..., "is_current": ...}, or null until its default expansion has been computed.
    • No query per row: the view gets it in the list query itself, through subqueries on the default expansion (Collection.annotate_expansion_health).
  • A version's detail returns the same field, looked up once.
  • Nested version lists (an expansion's explicit and evaluated versions, references' resolved versions) don't carry the field. CollectionVersionListSerializer includes it only when the view annotated it, so those lists don't gain a query per row.
  • Exports leave it out: it's in VERSION_EXPORT_EXCLUDED_FIELDS, next to verification. An export doesn't carry a health snapshot that goes stale.

Member lists

  • ?includeHealth=true on an expansion's concepts or mappings list adds health: {"class": ..., "references": [reference URLs]} to each member on the page.
    • Scope: it's computed for that page only (ExpansionHealth.classify(resource_type, page ids)), and paginated like the list.
    • Rows: each row is matched to its class by the row's own uuid where it has one, and by position otherwise (DRF serializes the page in order).
    • The toggle: the parameter is ignored while EXPANSION_HEALTH_TOGGLE is off.
    • Swagger: it's documented as include_health_param on both lists.

Tests

In core/collections/tests/tests_health.py:

  • expansion detail and list show health to a viewer
  • the versions list shows each default expansion's state, and null for a version without one
  • version detail shows it
  • version lists nested in an expansion carry no expansion_health
  • the verbose versions list shows the state too
  • version exports leave expansion_health out
  • includeHealth adds the class and reference URLs only when asked, for concepts and mappings
  • includeHealth is ignored with the toggle off

pylint -j0 core/ exits 0. core.collections.tests.tests_health passes locally, together with TasksTest (100 tests), run in a throwaway container from the API image against a fresh test database.

🤖 Generated with Claude Code

…nsions, the default expansion's state on collection versions, includeHealth on member lists
@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.

Review (8beb0d9). Verdict: changes needed before merge. One important finding and two nits; I'm fixing all three next.

The API part is right:

  • Expansions: list and detail return the stored health and health_is_current, read-only.
  • Versions list: it gets each default expansion's state through subqueries in the same query, so there's no query per row. Nested version lists (expansions, references) leave the field out.
  • Member lists: ?includeHealth=true classifies only the page's ids, and only while the toggle is on.
  • No stale cache: the cached first-page path in ListWithHeadersMixin applies only to source children, so these expansion lists aren't cached and can't serve stale health.
  1. Important: collection version exports now include expansion_health (inline). It's a snapshot that goes stale on the next recompute.
  2. Nit: includeHealth isn't in the Swagger docs.
  3. Nit: two paths have no test: the verbose versions list, and mappings with includeHealth.

CI: Snyk passed; Pylint and the test run are pending.

'immutable', 'revision_date', 'summary', 'text', 'experimental', 'locked_date',
'autoexpand', 'expansion_url', 'checksums', 'states', 'tasks', 'external_exports', 'verification'
'autoexpand', 'expansion_url', 'checksums', 'states', 'tasks', 'external_exports', 'verification',
'expansion_health'

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: this also reaches every collection version export. CollectionVersionExportSerializer exports all of this serializer's fields except VERSION_EXPORT_EXCLUDED_FIELDS ({'verification'}).

So exports now carry a health snapshot that goes stale on the next recompute, two exports of an unchanged version can differ by it alone, and each export runs one more query. Exclude it the way verification is excluded:

VERSION_EXPORT_EXCLUDED_FIELDS = {'verification', 'expansion_health'}

Also add a test that the export leaves it out.

Comment thread core/collections/views.py
self.expansion = expansion # pylint: disable=attribute-defined-outside-init
return expansion

def serialize_list(self, results, paginator=None):

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): includeHealth isn't documented. Other include* parameters are declared through swagger_auto_schema(manual_parameters=[...]), so /swagger/ shows no way to get member classes. Add an include_health_param and attach it to the concepts and mappings list views' get.

url = self.expansion.uri + 'concepts/'

plain = self.client.get(url)
with_health = self.client.get(url + '?includeHealth=true')

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): two paths this PR serves have no test:

  • The verbose versions list: CollectionVersionDetailSerializer on the annotated queryset.
  • Mappings with includeHealth: health_resource_type = 'mappings'.

A one-assertion test each would cover them.

… expansion_health; includeHealth documented; verbose versions and mapping health tested
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

All three review points are addressed in the latest commit. The description is updated.

  1. Exports (important): expansion_health is added to VERSION_EXPORT_EXCLUDED_FIELDS, next to verification, so collection version exports leave it out. A test checks the export serializer's fields.
  2. Swagger: a new include_health_param is attached to the concepts and mappings list views' get.
  3. Tests:
    • the verbose versions list shows each default expansion's state
    • ?includeHealth=true on an expansion's mappings list adds the class and the reference

pylint -j0 core/ exits 0. core.collections.tests.tests_health passes locally: 45 tests, run in a throwaway container from the API image against a fresh test database.

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

Second review (c824c17). Verdict: approved, ready to merge once CI is green and the stack below it has merged. No open findings.

The first review's three points are resolved:

  • Exports: expansion_health is in VERSION_EXPORT_EXCLUDED_FIELDS. Source exports use the same set and don't have the field, so they're unaffected.
  • Swagger: include_health_param is on CollectionVersionExpansionChildrenView.get, which both the concepts and mappings lists inherit.
  • Tests: the verbose versions list and the mappings includeHealth path are tested.

The PR as a whole:

  • Expansions: stored health is read-only on the list and detail.
  • Versions list: the default expansion's state comes from subqueries in the list query, so there's no query per row, and nested version lists and exports leave it out.
  • Member lists: includeHealth classifies only the page's ids, and only while the toggle is on.
  • No writes: nothing changes for production while EXPANSION_HEALTH_TOGGLE is off.
  • Local run: core.collections.tests.tests_health passes, 45 tests.

Merge order: #1025, then #1026 (retargeted to master), then this one (retargeted to master).

CI: Snyk passed; Pylint and the test run are pending.

@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 b3c0caf. An independent defect pass (Codex, high effort), with every finding checked against the code. Points from today's earlier read that you've already fixed aren't repeated.

Verdict: request changes, for point 1.

Must fix before merge

  1. /versions/?csv=true returns a 500. get_queryset now annotates every versions-list queryset (views.py ~819). get_csv falls back to queryset.values() (common/mixins.py ~376). djqscsv's write_csv then starts from query.values_select, a tuple on Django 5.2, and does field_names += list(annotation_select): TypeError. This doesn't depend on the toggle, so it breaks for any API user as soon as it's deployed. Suggestion inline: annotate only when the request isn't a CSV export. Please add a regression test for /versions/?csv=true with write_csv_to_s3 mocked.

Before merge, no code change
2. Merge master first. Master's new viewable-versions filter on the expansions list (from today) covers private versions' expansions there. git merge-tree with master is clean.

Worth fixing
3. Nested serializers do a lookup per row and throw it away. to_representation calls super() first, which runs get_expansion_health (serializers.py ~133-142), so every embedded collection version with an expansion_uri costs a query before the field is popped. That hits a concept's or mapping's collection-versions list, expansion version lists and reference resolution, whatever the toggle. Suggestion inline: return None unless the row was annotated.
4. The default-expansion lookup matches by URI only (models.py ~412, ~423). Collection.expansion scopes to self.expansions. Versions created before #950 could point at another collection's expansion, and would show its health. Suggestion inline: add collection_version_id.
5. ?includeHealth=true on one page does the whole collection's work. classify resolves every include reference (health.py ~53, 68, 104) before looking at the page, and an empty page does the same work. That's fine until TBv3 calls it, but due before #3004 uses it. Return early on an empty page, read the page's attributions first, and resolve only the references attributed to it.

Minor
6. The row-alignment test gives both rows the same class, so swapped rows would pass. Use two members of different classes.

Comment thread core/collections/models.py Outdated
Comment on lines +412 to +424
default_expansion = Expansion.objects.filter(uri=models.OuterRef('expansion_uri'))
return queryset.annotate(
expansion_health_state=models.Subquery(default_expansion.values('health__state')[:1]),
expansion_health_is_current=models.Subquery(default_expansion.values('health_is_current')[:1]))

@staticmethod
def get_expansion_health(version):
"""{state, is_current} of the version's default expansion; None until it has been computed"""
if hasattr(version, 'expansion_health_state'):
state, is_current = version.expansion_health_state, version.expansion_health_is_current
elif version.expansion_uri:
state, is_current = Expansion.objects.filter(uri=version.expansion_uri).values_list(
'health__state', 'health_is_current').first() or (None, 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 4: scopes both lookups to this version's own expansions (collection_version_id), as Collection.expansion does.

Suggested change
default_expansion = Expansion.objects.filter(uri=models.OuterRef('expansion_uri'))
return queryset.annotate(
expansion_health_state=models.Subquery(default_expansion.values('health__state')[:1]),
expansion_health_is_current=models.Subquery(default_expansion.values('health_is_current')[:1]))
@staticmethod
def get_expansion_health(version):
"""{state, is_current} of the version's default expansion; None until it has been computed"""
if hasattr(version, 'expansion_health_state'):
state, is_current = version.expansion_health_state, version.expansion_health_is_current
elif version.expansion_uri:
state, is_current = Expansion.objects.filter(uri=version.expansion_uri).values_list(
'health__state', 'health_is_current').first() or (None, None)
default_expansion = Expansion.objects.filter(
uri=models.OuterRef('expansion_uri'), collection_version_id=models.OuterRef('id'))
return queryset.annotate(
expansion_health_state=models.Subquery(default_expansion.values('health__state')[:1]),
expansion_health_is_current=models.Subquery(default_expansion.values('health_is_current')[:1]))
@staticmethod
def get_expansion_health(version):
"""{state, is_current} of the version's default expansion; None until it has been computed"""
if hasattr(version, 'expansion_health_state'):
state, is_current = version.expansion_health_state, version.expansion_health_is_current
elif version.expansion_uri:
state, is_current = version.expansions.filter(uri=version.expansion_uri).values_list(
'health__state', 'health_is_current').first() or (None, None)

Comment thread core/collections/serializers.py Outdated

@staticmethod
def get_expansion_health(obj):
return Collection.get_expansion_health(obj)

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: looks up health only on rows the versions list annotated; every other row drops the field anyway.

Suggested change
return Collection.get_expansion_health(obj)
return Collection.get_expansion_health(obj) if hasattr(obj, 'expansion_health_state') else None

Comment thread core/collections/views.py Outdated
if self.released_filter is not None:
queryset = queryset.filter(released=self.released_filter)
return queryset.order_by('-created_at')
return Collection.annotate_expansion_health(queryset).order_by('-created_at')

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: annotates only when the request isn't a CSV export, so get_csv's queryset.values() stays plain for djqscsv.

Suggested change
return Collection.annotate_expansion_health(queryset).order_by('-created_at')
if not self.request.query_params.get('csv'): # djqscsv can't write values() that carry annotations
queryset = Collection.annotate_expansion_health(queryset)
return queryset.order_by('-created_at')

# Conflicts:
#	core/collections/tests/tests_health.py
… nested version lists look up no health, and the default expansion lookup is scoped to its version
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Thanks, Jon. All six points are addressed. The fixes are in the latest commit, on a merge of the storage branch (70d0cfe), which carries master and the classifier and storage fixes.

  1. /versions/?csv=true (must fix): applied your suggestion: the health annotation is skipped for a CSV export, so djqscsv gets plain values(). A regression test mocks only the S3 service, so the real CSV writer runs on the queryset; it returns 200 with the URL.
  2. Merging master: done at the bottom of the stack (e027800 on the classifier branch) and merged up, so this branch has master's viewable-versions filter on the expansions list.
  3. Nested serializers: applied. CollectionVersionListSerializer looks up health only on rows the versions list annotated, so embedded collection versions cost no query.
  4. The default-expansion lookup: applied. The annotation and get_expansion_health are both scoped to the version's own expansions (collection_version_id / version.expansions).
  5. ?includeHealth=true on one page: fixed in the classifier (OpenConceptLab/ocl_issues#3003 | expansion health classifier (PR 1 of 4) #1025, e89e9c5). classify() resolves only the references the page's members are attributed to, and an empty page returns without a query.
  6. The row-alignment test: it now uses a release member next to the HEAD member, and checks first that their classes differ, so swapped rows fail.

Also from #1025, point 1: health is kept for default expansions only, so an expansion that isn't a version's default now reads health: null here.

The local Elasticsearch container is down, so CI is the 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.

Thanks, Sunny. All six points are met:

  1. The CSV export works, and the regression test runs the real writer.
  2. Master is merged in.
  3. Nested version lists look up no health.
  4. Both default-expansion lookups are scoped to the version.
  5. A page resolves only its own references (#1025).
  6. The row-alignment test now fails on swapped rows.

This approval covers this PR's own changes. Its CI failures come from #1025 and #1026 below it, and clear with their fixes.

@snyaggarwal

Copy link
Copy Markdown
Contributor Author

CI: the failing health tests came from the classifier and storage branches. Their fixes are merged in (a58e8ef). No change on this branch.

@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 lead (Claude, for Jon), round 3

This branch hasn't changed since round 2 apart from merging in the storage branch's fixes. CI is green at a58e8ef. Approval stands for this PR's own changes. It merges after #1026, which still has changes requested.

@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Merged #1026's latest (d637afc): #1025's pinned-repository cost fix and #1026's revision, nightly and dropped-children fixes. No change on this branch.

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