Skip to content

OpenConceptLab/ocl_issues#3003 | expansion health stored and kept current (PR 2 of 4, stacked on #1025) - #1026

Open
snyaggarwal wants to merge 10 commits into
issues-3003-expansion-health-classifierfrom
issues-3003-expansion-health-storage
Open

snyaggarwal wants to merge 10 commits into
issues-3003-expansion-health-classifierfrom
issues-3003-expansion-health-storage

Conversation

@snyaggarwal

@snyaggarwal snyaggarwal commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR 2 of 4 for OpenConceptLab/ocl_issues#3003, stacked on #1025 (the classifier). Its base is that branch, so this diff shows only PR 2. Merge #1025 first, then retarget this PR to master.

The expansion now stores its health summary and keeps it current. There's still no API (PR 3) and no backfill (PR 4).

Storage

  • Two nullable columns on Expansion (migration 0074_expansion_health, no backfill):
    • health: the ExpansionHealth.compute() summary.
    • health_is_current has three states:
      • true: it matches the members.
      • false: out of date, with a recompute queued.
      • null: not current, with nothing queued. That's never computed, a failed computation, or a repo version change; the next change queues a recompute.
  • Health writes: they go through their own UPDATEs. Expansion.save() without update_fields now leaves out the two health fields, so a long-running task saving an older copy of the expansion can't put back stale health.
  • Behaviour change outside the toggle: that save() override applies whatever EXPANSION_HEALTH_TOGGLE says. Saving a loaded expansion whose row has since been deleted now raises Django's Save with update_fields did not affect any rows, instead of silently inserting the deleted expansion again. For example, a long seed task finishing after its collection version was deleted. Re-inserting a deleted expansion was itself wrong.

When it's computed (decision 3)

  • Build and rebuild: at the end of seed_children_to_expansion, after the members are written and processing is cleared.
  • The copy at version create: at the end of Collection.seed_from_head_expansion, for lock or latest. A version built through cascade_children_to_expansion goes through seed_children_to_expansion and is covered by the build case.
  • Adds and removals: Collection.add_references (when it added any) and both delete_references paths call mark_health_out_of_date(). The re-add task that follows a removal calls it again once it has changed the members.
  • Debounce: mark_health_out_of_date() flips health_is_current to false with one conditional UPDATE. Only the call that flips it queues compute_expansion_health, on commit, after 60 seconds (EXPANSION_HEALTH_DEBOUNCE_SECONDS). A bulk import that adds references many times queues one recompute.
  • A change during a recompute: update_health() sets the flag back to true when it starts. A change while it computes marks the expansion out of date again and queues another run.
  • Failures: they're logged and leave health_is_current null, so the next change recomputes. They never fail the build.
  • Repo version changes: releasing, retiring, deactivating or deleting a source or collection version sets health_is_current to null on every expansion that recorded a version of that repository. Classes read those versions. It's one set-based UPDATE, with no task per expansion, so a CIEL release doesn't queue thousands of recomputes. Those expansions are recomputed by their next change, or by PR 4's command.
  • In TEST_MODE: the recompute runs inline, as other tasks here do, so tests need no Redis.

Toggle

EXPANSION_HEALTH_TOGGLE (pk 12) is on for dev, QA and staging and off for production. With it off nothing is computed or written, and expansions behave as before apart from the two new null columns.

Tests

In core/collections/tests/tests_health.py:

  • health is stored at build, after an add and after a removal
  • one add of three references recomputes once
  • an expansion already out of date queues no second recompute
  • toggle off writes nothing
  • a failing computation leaves health not current and the build done, and the next change recomputes it
  • releasing, retiring or deleting a version of a recorded repository leaves health not current; an unrelated save doesn't
  • a save from an older copy keeps the stored health
  • a version created from HEAD stores health

pylint -j0 core/ exits 0. The local oclapi2 stack is down, so the tests run in CI only. I couldn't run makemigrations --check locally, because the local venv fails to import Elasticsearch. The migration mirrors the two field definitions.

Since Jon's Nov 23 review

  • Default expansions only: health is kept for each version's default expansion; any other expansion stores null.

  • No stale "current": health_revision (in 0074) is bumped by every mark. A computation stores its result as current only if the revision is unchanged since it started; otherwise it queues a fresh run.

  • What marks health:

    • edits in HEAD (a version leaving or re-entering it), with a debounced recompute;
    • value-set changes;
    • hard deletes;
    • public_access and expansion_uri changes;
    • repository deletes, again on commit.

    Marks also happen with the toggle off, as not current with nothing queued.

  • Nightly recheck: a beat task at 2 am recomputes up to 1,000 default expansions a night whose health isn't current.

🤖 Generated with Claude Code

…sion, computed at build, rebuild and copy, recomputed after reference changes

@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 (619f921). Verdict: changes needed before merge. One important finding; two non-blocking notes.

The storage and triggers follow decision 3:

  • Build and rebuild: health is computed at the end of seed_children_to_expansion, which the rebuild view also uses.
  • Version create: it's computed at the end of seed_from_head_expansion, after the HEAD rows are swapped. A version built through cascade_children_to_expansion is covered by the build task.
  • Reference changes: adds, both removal paths and the re-add task mark health out of date, with a debounced, on-commit recompute.
  • Dry runs: marks made inside rolled-back dry-run transactions are rolled back, and their on_commit callbacks never fire.
  • Toggle off: nothing is computed or written.
  1. Important: a failed computation stops all later recomputes (inline). Failure leaves health_is_current = False, which mark_health_out_of_date reads as "a recompute is already queued".
  2. Nit: health goes stale when repo versions change. Releasing, retiring or deleting a source version doesn't mark dependent expansions out of date. That's outside decision 3's triggers, but worth a plan.
  3. Nit: the save() override applies with the toggle off. A save of an expansion whose row was deleted now raises instead of re-inserting it.

CI: Snyk passed and Pylint is pending. The tests haven't run on this commit yet.

Comment thread core/collections/models.py Outdated
health = ExpansionHealth(self).compute()
except Exception: # pylint: disable=broad-except
logger.exception('Expansion health failed for %s', self.uri)
Expansion.objects.filter(id=self.id).update(health_is_current=False)

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 failed computation stops all later recomputes. This sets health_is_current = False without queueing anything. mark_health_out_of_date treats False as "a recompute is already queued" and returns, so after one failure, for example a transient database error in the build's update_health, no later add or removal recomputes health until someone rebuilds the expansion.

Use None for "not current, nothing queued". mark_health_out_of_date already flips None and queues:

Suggested change
Expansion.objects.filter(id=self.id).update(health_is_current=False)
Expansion.objects.filter(id=self.id).update(health_is_current=None)

Then test_a_failure_leaves_health_out_of_date_and_the_build_done should expect (None, None). A second test, where an add after a failed compute does recompute, would pin it down.

Comment thread core/collections/models.py Outdated
if not self.is_health_on():
return
self.health_is_current = False
if not Expansion.objects.filter(id=self.id).exclude(health_is_current=False).update(health_is_current=False):

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): health can go stale while still marked current. Only builds, copies and reference changes mark it out of date. But classes also depend on repo versions:

  • whether a holder is released
  • whether a release or HEAD holds a member
  • which version an unversioned reference resolves to

Releasing, retiring or deleting a source version changes those without touching the expansion. For example, members counted as interim stay interim after a release starts holding them.

That's outside decision 3, so it's not for this PR. Either PR 4's command recomputes by age or rules_version, or #3001's delete-time record also marks dependent expansions out of date. Worth a line in the plan.

'collection_owner_url': [self.owner_url],
}

def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=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): this override applies whatever the toggle says. Every save of a loaded expansion now goes through update_fields, so saving one whose row has been deleted raises Save with update_fields did not affect any rows instead of silently inserting it again. For example, a long seed task finishes after its collection version was deleted.

Raising is arguably better, since re-inserting a deleted expansion was itself wrong. But it's a behaviour change outside the toggle, so say so in the PR description.

…d on the next change; releasing, retiring or deleting a repo version leaves dependent expansions not current
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

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

  1. Failed computation (important): a failure now leaves health_is_current null, meaning not current with nothing queued. The next change then flips it and queues a recompute. The failure test expects (None, None), and a new test shows that an add after a failure recomputes.
  2. Repo version changes: Source.save and Collection.save set health_is_current to null on every expansion that recorded a version of the repository. They do it when released, retired or is_active changes on a saved version, and so does ConceptContainerModel.delete, before the rows go. It's one set-based UPDATE, with no task per expansion, so a CIEL release doesn't queue thousands of recomputes. Those expansions are recomputed by their next change, or by PR 4's command, which can pick up everything that isn't current. Tests cover release, retire and delete. Another checks that a save changing none of those fields leaves health current, and that an unrelated expansion stays current.
  3. The save() override: now documented in the description as a behaviour change outside the toggle. Saving a deleted expansion raises instead of re-inserting it.

pylint -j0 core/ exits 0. The tests run in CI only, since the local oclapi2 stack is down.

@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 (30dade1). Verdict: changes needed before merge. CI is red: four existing tests fail. The code itself looks right.

The first review's points are resolved:

  • A failed computation leaves health_is_current null, meaning not current with nothing queued, so the next change recomputes.
  • Releasing, retiring, deactivating or deleting a source or collection version sets null on every expansion that recorded a version of the repository. It's one set-based UPDATE, it skips new versions, and on delete it runs before the rows go. Expansions already queued (false) are left alone, since their pending recompute reads the new state.
  • The save() behaviour change is documented in the description.

Blocking: four TasksTest removal tests fail (inline). They run with TEST_MODE off and capture on_commit callbacks. remove_references now also queues compute_expansion_health:

  • Three errors: they reach apply_async, which needs Redis, and GHA has none.
  • One failure: test_remove_references_with_toggle_off_queues_at_once_before_deleting asserts no callbacks at all.

These tests count the re-add's callbacks and tasks, so switching the health toggle off in them is the right fix. No code change is needed.

Non-blocking, no change requested: a repository deactivated through QuerySet.update (for example when an organization is deactivated) doesn't go through save(), so its expansions aren't marked. Deactivated repositories' health matters less, and PR 4's command can sweep them.

CI: Pylint and Snyk passed; Tests failed (3,514 run: 1 failure, 3 errors).

Comment thread core/collections/models.py Outdated
compute_expansion_health(self.id)
else:
expansion_id = self.id
transaction.on_commit(lambda: compute_expansion_health.apply_async(

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 callback breaks four existing removal tests in core/collections/tests/tests.py:

  • test_remove_references_queues_readd_after_the_references_are_gone
  • test_remove_references_queues_readd_when_indexing_fails
  • test_seed_children_task_evaluates_references_while_a_removal_awaits_its_readd
  • test_remove_references_with_toggle_off_queues_at_once_before_deleting

They run with TEST_MODE off and execute or inspect on_commit callbacks. remove_references now registers this one too:

  • Three error out: apply_async pings Redis, and GHA has none.
  • The fourth fails: it asserts callbacks == [].

They test the re-add's queueing, so switch health off in them, for example with @patch('core.collections.models.Expansion.is_health_on', Mock(return_value=False)). The code here doesn't need to change.

…s callbacks and tasks run with expansion health off
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Fixed in the latest commit. The four TasksTest removal tests now run with expansion health switched off (@patch('core.collections.models.Expansion.is_health_on', Mock(return_value=False))):

  • test_remove_references_queues_readd_after_the_references_are_gone
  • test_remove_references_queues_readd_when_indexing_fails
  • test_seed_children_task_evaluates_references_while_a_removal_awaits_its_readd
  • test_remove_references_with_toggle_off_queues_at_once_before_deleting

They check the re-add's queueing and on_commit callbacks, so health's own recompute shouldn't count there. The health tests in tests_health.py cover the recompute itself. There's no code change. pylint -j0 core/ exits 0.

@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 a0dac37. An independent defect pass (Codex, high effort), with every finding checked against the code. Nobody had read this PR before today's pass, so this is its first outside review.

Verdict: comment. Please fix point 1 in this PR before it merges. The toggle being off makes merging safe. But point 1 is the case health exists to show, and it's cheapest to fix while the marking code is still open.

Before the toggle goes on in production

  1. Editing a concept or mapping in HEAD leaves stored health marked current. save_as_new_version calls prev_latest.unmark_latest_version(...) (common/mixins.py ~1263), which removes the old version from the source's HEAD (sources.remove(parent), ~1143). Expansions that hold the old version keep it, so those members are now interim. Nothing on that path marks health: only reference add and remove, and saves of released / retired / is_active, do (collections/models.py ~311, 346, 359; sources/models.py ~951). A HEAD-resolved or healthy summary therefore stays current after an ordinary edit. Fix: when a version leaves or re-enters HEAD (unmark_latest_version, mark_latest_version, restore), mark the expansions that hold it. That's one indexed UPDATE on the membership table, behind the toggle. Then queue the debounced recompute rather than only nulling, because a frozen release never gets a "next change". Please add a test: edit a concept held by a HEAD-resolved expansion.
  2. A failed publish strands the row. mark_health_out_of_date (~2549-2556) sets health_is_current=False, then publishes in on_commit. If apply_async raises (a Redis failover), nothing is queued. Later marks skip rows that are already False, so only a rebuild or the backfill recovers it. Suggestion inline: catch the failure, log it, and reset to None so the next change requeues.
  3. Current but stale. update_health (~2511-2528) sets health_is_current=True before computing and writes health after. A worker killed mid-compute (a deploy, OOM) leaves the old summary marked current. With acks_late and the 72 h visibility timeout, redelivery can come days later. Readers also see True with the old summary during every compute. Fix: a revision or start token that mark_health_out_of_date bumps. Write health and True in one conditional UPDATE, only if the revision hasn't changed; otherwise requeue. Migration 0074 is still unmerged, so the column can go there. #1031's interrupted --apply hits the same root.
  4. Marking stops while the toggle is off. mark_health_out_of_date and mark_health_not_current_for_repository return early when the toggle is off. Switching it on, off and on again (the rollback path) leaves stale rows labelled current, and the backfill's --all skips them. Fix: keep the cheap marking (set the flag to None, queue nothing) while it's off, and skip only the compute. Failing that, add a runbook line: after any off period, run the backfill with --force.

Smaller
5. Value set A changes; value sets built on A's HEAD aren't marked. Value-set references are judged against the target version's default expansion, but a reference removal on A marks only A's expansion, and expansion_uri isn't in HEALTH_RELEVANT_VERSION_FIELDS. Null health on expansions that recorded that collection version.
6. Add and remove mark only the default expansion (~305-311, 351-359). Other expansions of the same version are judged by the version's current references. This goes away once health is limited to default expansions (#1025, point 1).
7. A hard delete of a concept or mapping cascades the membership rows without marking. It's admin-only and rare, so null health by member id first.
8. Delete-time race. ConceptContainerModel.delete marks only rows that are True (~2541). A row already False whose recompute runs before the delete commits stores pre-delete classes as current. Capture the affected ids before deleting, whatever their flag, and null them on commit.
9. public_access belongs in HEALTH_RELEVANT_VERSION_FIELDS, since the visibility filter reads it. Suggestion inline.
10. test_toggle_off_writes_no_health checks the newly built expansion, not the one the add changes. It would still pass with the toggle guard removed. Suggestion inline.

Ops note: publishing, retiring or deactivating a version marks every expansion that recorded any version of that source as not current, which for CIEL could mean thousands. Frozen releases then stay not current until a backfill runs. Please add a nightly run of the backfill over rows that aren't current, in small batches. A follow-up PR is fine.

Comment thread core/collections/constants.py Outdated
EXPANSION_HEALTH_TOGGLE = 'EXPANSION_HEALTH_TOGGLE'
EXPANSION_HEALTH_DEBOUNCE_SECONDS = 60
# a repo version's fields that expansion health reads
HEALTH_RELEVANT_VERSION_FIELDS = {'released', 'retired', 'is_active'}

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 9: a visibility change marks expansions that recorded the repository, since the visibility filter reads it.

Suggested change
HEALTH_RELEVANT_VERSION_FIELDS = {'released', 'retired', 'is_active'}
HEALTH_RELEVANT_VERSION_FIELDS = {'released', 'retired', 'is_active', 'public_access'}

Comment thread core/collections/models.py Outdated
Comment on lines +2554 to +2556
expansion_id = self.id
transaction.on_commit(lambda: compute_expansion_health.apply_async(
(expansion_id,), queue='default', countdown=EXPANSION_HEALTH_DEBOUNCE_SECONDS))

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: a failure to queue is logged and resets the flag to None, so the next change requeues.

Suggested change
expansion_id = self.id
transaction.on_commit(lambda: compute_expansion_health.apply_async(
(expansion_id,), queue='default', countdown=EXPANSION_HEALTH_DEBOUNCE_SECONDS))
expansion_id = self.id
def queue_recompute():
try:
compute_expansion_health.apply_async(
(expansion_id,), queue='default', countdown=EXPANSION_HEALTH_DEBOUNCE_SECONDS)
except Exception: # pylint: disable=broad-except
logger.exception('Could not queue expansion health for %s', expansion_id)
# None, not False: nothing is queued, so the next change queues a recompute
Expansion.objects.filter(id=expansion_id, health_is_current=False).update(health_is_current=None)
transaction.on_commit(queue_recompute)

Comment thread core/collections/tests/tests_health.py Outdated
Comment on lines +493 to +497
with patch.object(Expansion, 'is_health_on', return_value=False):
expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
self.add(ConceptFactory())

self.assertEqual(

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 10: also checks the default expansion the add changes, so the test fails if the toggle guard in mark_health_out_of_date goes. If you take point 4 (keep marking while the toggle is off), assert instead that is_current is None and nothing was queued.

Suggested change
with patch.object(Expansion, 'is_health_on', return_value=False):
expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
self.add(ConceptFactory())
self.assertEqual(
before = self.stored()
with patch.object(Expansion, 'is_health_on', return_value=False):
expansion = Expansion.persist(index=False, collection_version=self.collection, mnemonic='other')
self.add(ConceptFactory())
# the add changed the default expansion's members but not its stored health
self.assertEqual(self.stored(), before)
self.assertEqual(

…s, stored as current only if unchanged while computing, marked on HEAD edits, deletes and value-set changes, and rechecked nightly
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Thanks, Jon. All ten points and the ops note are addressed in f63ff30. The classifier's fixes and master are merged in first, in adb3dee.

  1. Edits in HEAD: when a version leaves or re-enters HEAD (unmark_latest_version, mark_latest_version, restore_to_head), the default expansions holding it are marked out of date in one query. Each one that wasn't already out of date gets the debounced recompute, so a frozen release is recomputed too. Test: a member taken out of HEAD is recomputed as interim.
  2. A failed publish: your suggestion, as queue_health_recompute. If queuing fails, it's logged and the flag resets to None, so the next change queues again. Test added.
  3. Current but stale: there's a new health_revision column, in 0074. Every mark bumps it. update_health no longer sets True before computing. It writes health and True in one conditional UPDATE, only if the revision hasn't changed; otherwise it queues a fresh run. A killed worker therefore leaves the row not current rather than stale, which also covers OpenConceptLab/ocl_issues#3003 | expansion health backfill (PR 4 of 4, stacked on #1029) #1031's interrupted --apply. Test: a change during the computation isn't stored as current.
  4. Marking with the toggle off: marks still happen while the toggle is off. Rows are set to None and nothing is queued, so --all finds them once health is on again. Repository marks no longer check the toggle at all.
  5. A changed value set: adding or removing references on a collection version now nulls the health of expansions that recorded that version in their collection lists. expansion_uri is now a health-relevant field. Test added.
  6. Other expansions: this goes away, because health is kept for the default expansion only (OpenConceptLab/ocl_issues#3003 | expansion health classifier (PR 1 of 4) #1025, point 1). Any other expansion stores null. Test added.
  7. Hard deletes: a concept's or mapping's hard delete nulls the health of the expansions holding it, and its versions, before the cascade. That covers the model delete() and the raw db=true path. Test added.
  8. The delete race: the repository delete captures the affected expansion ids before deleting, whatever their flag, and nulls them again on commit. Test: a recompute stored before the delete committed isn't left current.
  9. public_access: added to HEALTH_RELEVANT_VERSION_FIELDS. Test added.
  10. The toggle-off test: it now checks the default expansion: still marked, the summary untouched, nothing computed.

Ops note: there's a nightly recheck_expansion_health beat task at 2 am. It recomputes up to 1,000 default expansions a night whose health is None, and leaves ones with a run queued (False) to that run. Tests added.

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. Points 2 and 4 to 10 are met, and so is the ops note. Migration 0074 is metadata-only on Postgres 14, so nothing is rewritten. It does take a brief exclusive lock, so deploy it off-peak or with a lock_timeout.

CI fails five of this PR's own tests (test_build_stores_health and four more in ExpansionHealthStorageTest). The setUp persists the expansion, which in TEST_MODE builds it at once, and only then sets collection.expansion_uri. So update_health sees an expansion that isn't the default and stores null. Set the default first in setUp, or recompute after it. #1031's two failing backfill tests have the same cause.

  • In production, the default is claimed before seeding only when the locked-repo-version toggle is on. Otherwise it's set after persist returns, and the async seed normally starts later. A seed that ever runs first leaves that expansion's health null until the nightly recheck, which is acceptable.

Point 3: stale health can still be stored as current. Both fixes are small, with suggestions inline.

  • An expansion already out of date:
    • the row is False and run R is queued; R reads revision r;
    • a change T touches members, and T's first UPDATE matches nothing (the row is False), so nothing is bumped;
    • R stores True at r; T then bumps the revision only, and queues nothing.
    • Health stays current with the old members, and on a frozen release it stays that way. Bump first, then flip.
  • A rebuild: neither a rebuild nor a store bumps the revision.
    • A backfill or nightly run reads r; the owner re-evaluates; the rebuild stores fresh health at r.
    • The older run then stores too, and its filter on r still matches.
    • Bump on store, so the second store fails and requeues.

Rows stuck at False (suggestion inline): the nightly skips False rows, and every later mark sees False and queues nothing. A row gets stuck when:

  • a run fires while the toggle is off (on, off, then on again);
  • a compute fails after a mark bumped the revision;
  • or the queued message is lost.

The nightly can safely take False rows too, since a store checks the revision.

Point 1, one path missed: Source.drop_unseen_children (core/sources/models.py, from the isolated-version seeding import) removes versioned objects and their latest rows from HEAD in bulk, and marks nothing. It's outside this diff. After the through-table delete, call Expansion.mark_health_out_of_date_for_members(...) with the chunk and the latest ids.

Before health is turned on in production:

  • Concept edits: mark_health_out_of_date_for_members loads full rows, then for each expansion reads the toggle (uncached) and runs one or two UPDATEs, all inside the versioned-object lock of a concept edit. A widely used concept sits in dozens of default expansions, so one edit costs hundreds of queries. Make it set-based:
    • return early when there are no ids;
    • bump them all in one UPDATE, and set the ones not already False to False in one more;
    • then queue each.
  • Hard deletes (core/common/mixins.py:679-685, core/concepts/views.py:494-497) mark in autocommit before deleting, so a run in between stores pre-delete health as current. Re-mark the captured ids after the delete, as point 8 does.
  • The nightly runs serially in one task, by id, with a cap. If 1,000 or more rows fail every night, they're retried first each time and starve the rest. Fan it out per id, or order by when each was last tried.
  • Value-set marks: mark_health_not_current_for_value_set ORs two M2M joins and scans the expansions table on every reference add or remove, with the toggle on or off. Two through-table lookups by collection id would use the index.

Comment thread core/collections/models.py Outdated
Comment on lines +2585 to +2586
if not expansions.filter(health_revision=revision).update(health=health, health_is_current=True):
# marked while it computed: a fresh run reads the change

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.

The store bumps the revision too, so an older run that ends after a newer one can't overwrite it.

Suggested change
if not expansions.filter(health_revision=revision).update(health=health, health_is_current=True):
# marked while it computed: a fresh run reads the change
# the store bumps it too, so an older run that ends after a newer one (a rebuild's) can't overwrite it
if not expansions.filter(health_revision=revision).update(
health=health, health_is_current=True, health_revision=F('health_revision') + 1):
# marked, or stored by a newer run, while it computed: a fresh run reads the change

Comment thread core/collections/models.py Outdated
Comment on lines +2670 to +2675
self.health_is_current = False
if not expansions.exclude(health_is_current=False).update(health_is_current=False, health_revision=bump):
# already out of date: its queued run reads this change too
expansions.update(health_revision=bump)
return
self.queue_health_recompute(self.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.

Bumped on its own first, so a run that read the old revision can't store its result as current, even when the row was already out of date.

Suggested change
self.health_is_current = False
if not expansions.exclude(health_is_current=False).update(health_is_current=False, health_revision=bump):
# already out of date: its queued run reads this change too
expansions.update(health_revision=bump)
return
self.queue_health_recompute(self.id)
self.health_is_current = False
# bumped on its own first, so a run that read the old revision can't then store its result as current
expansions.update(health_revision=bump)
if expansions.exclude(health_is_current=False).update(health_is_current=False):
self.queue_health_recompute(self.id)

Comment thread core/common/tasks.py Outdated
Comment on lines +518 to +526
"""Nightly: recomputes, a batch at a time, the default expansions whose health isn't current and has no run
queued. A release, retire or delete leaves them so, and a frozen release never gets another change"""
from django.db.models import F
from core.collections.constants import EXPANSION_HEALTH_RECHECK_LIMIT
from core.collections.models import Expansion
if not Expansion.is_health_on():
return 0
expansion_ids = list(Expansion.objects.filter(
health_is_current__isnull=True, is_processing=False, is_active=True, collection_version__is_active=True,

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.

Also takes rows left at False, whose queued run may never have come.

Suggested change
"""Nightly: recomputes, a batch at a time, the default expansions whose health isn't current and has no run
queued. A release, retire or delete leaves them so, and a frozen release never gets another change"""
from django.db.models import F
from core.collections.constants import EXPANSION_HEALTH_RECHECK_LIMIT
from core.collections.models import Expansion
if not Expansion.is_health_on():
return 0
expansion_ids = list(Expansion.objects.filter(
health_is_current__isnull=True, is_processing=False, is_active=True, collection_version__is_active=True,
"""Nightly: recomputes, a batch at a time, the default expansions whose health isn't current. A release, retire
or delete leaves them so, and a frozen release never gets another change. One with a run queued (False) is taken
too, in case that run never came: a duplicate is harmless, as a store checks the revision"""
from django.db.models import F
from core.collections.constants import EXPANSION_HEALTH_RECHECK_LIMIT
from core.collections.models import Expansion
if not Expansion.is_health_on():
return 0
expansion_ids = list(Expansion.objects.exclude(health_is_current=True).filter(
is_processing=False, is_active=True, collection_version__is_active=True,

Comment thread core/collections/tests/tests_health.py Outdated
Comment on lines +755 to +758
def test_the_nightly_recheck_leaves_queued_ones_to_their_run(self):
Expansion.objects.filter(id=self.expansion.id).update(health_is_current=False)

self.assertEqual(recheck_expansion_health(), 0)

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.

The test for that.

Suggested change
def test_the_nightly_recheck_leaves_queued_ones_to_their_run(self):
Expansion.objects.filter(id=self.expansion.id).update(health_is_current=False)
self.assertEqual(recheck_expansion_health(), 0)
def test_the_nightly_recheck_also_takes_ones_whose_queued_run_never_came(self):
Expansion.objects.filter(id=self.expansion.id).update(health_is_current=False)
self.assertEqual(recheck_expansion_health(), 1)
self.assertTrue(self.stored()[1])

…n is the version's default still stores health, and the storage tests claim the default before seeding
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

CI fix (3cacf5b): five storage tests failed because the test setUp seeded the expansion before making it the default. With health kept for the default expansion only, that seed stored none. The same gap existed in code: with the lock toggle off, cascade_children_to_expansion sets expansion_uri after the seed, so a seed that had already finished left a new version with no health until the nightly recheck. That branch now computes health when the finished seed stored none. Tests claim the default before seeding, as the toggle-on path does. The HEAD-edit test now references the version itself: a reference to the concept holds the HEAD concept, which is a mismatch, not a HEAD member. New test: a seed that ends before its expansion is the default still stores health. Merged the classifier fix (7737488).

@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

Thanks, Sunny. The CI fix is right. The storage tests now claim the default before seeding, as a version's own build does, and the HEAD-edit test references the version itself. The new branch in cascade_children_to_expansion closes the gap round 2 left to the nightly recheck, with one fix below. CI is green at 7737488.

New: the fallback computes from a stale copy (suggestion inline).

  • seed_children_to_expansion loads its own copy of the expansion and saves what it finds there, unresolved_repo_versions included.
  • The expansion this branch holds is the one persist returned, so its unresolved_repo_versions is still empty.
  • Wherever the locked-repo-version toggle is off and a reference doesn't resolve, health is stored as current without unresolved_references (or system_version_unresolved), and the nightly recheck then skips it.
  • Reload it before computing, and extend the new test with a reference that doesn't resolve.

Still open from round 2. Nothing has changed here since; round 2's inline suggestions still apply.

  1. Point 3, stale health stored as current:
    • mark_health_out_of_date still sets False before bumping, so a change to a row that's already False bumps only after a running compute may have stored at the old revision.
    • update_health still stores without bumping health_revision, so an older run that ends after a rebuild's still matches.
  2. Rows stuck at False: recheck_expansion_health still takes only null rows, so a False row whose queued run never came stays out of date.
  3. Point 1, Source.drop_unseen_children: it still marks nothing after its bulk delete.

Before health is turned on in production (unchanged, not blocking the merge):

  • make mark_health_out_of_date_for_members set-based;
  • re-mark after the two hard deletes;
  • fan out the nightly, or order it by last try;
  • run value-set marks through the two through tables.

Comment on lines +402 to +404
# a seed that ended before this made it the default stored no health
if Expansion.objects.filter(id=expansion.id, is_processing=False, health_is_current__isnull=True).exists():
expansion.update_health()

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.

The seed saved what it found, unresolved repositories included, on its own copy, so this one is stale.

Suggested change
# a seed that ended before this made it the default stored no health
if Expansion.objects.filter(id=expansion.id, is_processing=False, health_is_current__isnull=True).exists():
expansion.update_health()
# a seed that ended before this made it the default stored no health
if Expansion.objects.filter(id=expansion.id, is_processing=False, health_is_current__isnull=True).exists():
# the seed saved what it found (unresolved repositories among it) on its own copy
expansion.refresh_from_db()
expansion.update_health()

…pping and a store bumps it too, the nightly recheck takes rows left out of date, and dropped HEAD children mark their expansions
@snyaggarwal

Copy link
Copy Markdown
Contributor Author

Round 3 and round 2's open points are in 5b93c92; the merge of #1025's cost fix is 837bd4f. Its one conflict, in tests_health.py, was resolved in that merge commit on its own.

(a) The seed fallback computed from a stale copy. It now reloads the expansion (refresh_from_db()) before update_health(), as you suggested. test_a_seed_that_ends_before_its_expansion_is_the_default_still_stores_health now adds a reference to a missing source and asserts unresolved_references is 1 in the stored health.

(b) Point 3, stale health stored as current.

  • mark_health_out_of_date bumps health_revision on its own first, then flips the row to False and queues only if that flip matched a row.
  • update_health's conditional store also bumps the revision, so an older run that ends after a rebuild's store loses and requeues.
  • Two tests: one checks that a mark's first UPDATE sets only the revision; one checks that an older run ending after a newer store doesn't overwrite it.

(c) Rows stuck at False. recheck_expansion_health now takes every default expansion that isn't current (exclude(health_is_current=True)). Your test replaces the old "leaves queued ones" test.

Point 1, Source.drop_unseen_children. After each chunk's through-table delete, it calls Expansion.mark_health_out_of_date_for_members with the chunk and its latest ids. New test: a version-pinned member that the drop takes out of HEAD reads interim, with health current.

From "before health is turned on", one done here: mark_health_out_of_date_for_members is now set-based, because the drop calls it with chunks of up to 5,000 ids.

  • It returns early with no ids or no expansions.
  • One UPDATE bumps the revision on all of them, and one more flips to False the ones that weren't already.
  • It then queues each flipped one.

Still open from that list:

  • re-marking after the two hard deletes;
  • fanning out the nightly, or ordering it by last try;
  • running value-set marks through the two through tables.

None of these block the merge. Local Elasticsearch is down, so CI is the first run.

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