Skip to content

[RunInference] Retry failed model loads in multi-model KeyedModelHandler - #41405

Merged
damccorm merged 4 commits into
apache:masterfrom
karthik-0306:fix-keyed-model-load-failure
Nov 25, 2026
Merged

damccorm merged 4 commits into
apache:masterfrom
karthik-0306:fix-keyed-model-load-failure

Conversation

@karthik-0306

Copy link
Copy Markdown
Contributor

Fixes #41404

_ModelHandlerManager.load stored a key's tag in _tag_map before loading the model. If load_model() raised, for example on a transient GCS error, the tag stayed in _tag_map with no entry in _proxy_map. After that, every load(key) returned the stale tag, so the model was reloaded on every batch, and evicting or updating that key failed with KeyError: '<uuid>'.

This removes the key from _tag_map when the load fails, so the next batch loads the model again and it is cached like any other key.

Testing: added test_model_handler_manager_retries_failed_load, which fails on master and passes with the fix. The _ModelHandlerManager, KeyedModelHandler and ModelManagerTest tests pass. yapf and ruff are clean.

R: @damccorm

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📋 Review Summary

This PR fixes a bug in _ModelHandlerManager.load where a failure during shared_handle.acquire() left a stale tag in _tag_map without a corresponding entry in _proxy_map. Cleaning up self._tag_map[key] on exception ensures subsequent batches properly retry and cache the model load and prevents KeyError during LRU eviction or model updates.

🔍 General Feedback

  • The fix in sdks/python/apache_beam/ml/inference/base.py is minimal, targeted, and directly addresses the root cause of #41404.
  • The unit test test_model_handler_manager_retries_failed_load thoroughly covers failed initial loads, subsequent retry and caching behavior, and LRU eviction after recovery.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

@github-actions github-actions Bot added python size/s S: 10-49 lines changed labels Nov 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @claudevdm for label python.
Backup reviewer: jrmccluskey (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Comment on lines 728 to 735
try:
model_reference = shared_handle.acquire()
except Exception:
# Forget the tag so that the next call loads the model again instead of
# returning a tag that has no model behind it.
del self._tag_map[key]
raise
self._proxy_map[tag] = (shared_handle, model_reference)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for catching and fixing this! Instead of inserting self._tag_map[key] before loading and rolling it back on exception, could we defer setting self._tag_map[key] = tag until right after shared_handle.acquire() succeeds (next to self._proxy_map[tag] = (shared_handle, model_reference)) and adjust the LRU check above to self._max_models <= len(self._tag_map) and self._tag_map?

if key in self._tag_map:
  self._tag_map.move_to_end(key)
  return _ModelLoadStats(self._tag_map[key], None, None)

tag = uuid.uuid4().hex
mh = self._mh_map[key]

if (self._max_models is not None and
    self._max_models <= len(self._tag_map) and self._tag_map):
  # If we're about to exceed our LRU size, release the last used model.
  tag_to_remove = self._tag_map.popitem(last=False)[1]
  shared_handle, model_to_remove = self._proxy_map[tag_to_remove]
  shared_handle.release(model_to_remove)
  del self._proxy_map[tag_to_remove]

# Load the new model
memory_before = _get_current_process_memory_in_bytes()
start_time = _to_milliseconds(time.time_ns())
shared_handle = multi_process_shared.MultiProcessShared(
    mh.load_model, tag=tag)
model_reference = shared_handle.acquire()
self._tag_map[key] = tag
self._proxy_map[tag] = (shared_handle, model_reference)

That keeps _tag_map and _proxy_map strictly in sync while acquire() is in flight (avoiding a window on the multi-threaded MultiProcessShared manager where a concurrent load(key) sees a tag with no model behind it or an eviction/update_model_handler hits KeyError on _proxy_map[tag]), and also covers failures outside acquire() (e.g., self._mh_map[key] or BaseException) without needing a try/except rollback.

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.

Thanks for the review! I tried this version, but it changes one thing the current code relies on. load() gets called from several threads at once, since the shared manager serves calls on separate threads. Today, if a second load(key) comes in while the first one is still loading, it gets the same tag, and both share one model load. If _tag_map[key] is only set after acquire(), the second call doesn't see the key yet, so it loads its own copy under a new tag. When both finish, the first tag's proxy stays in _proxy_map and is never released. I checked this with two threads loading the same key: 1 load_model call and 1 proxy with the current code, and 2 calls and 2 proxies with the deferred insert. I also found two related cases: concurrent loads of different keys can go over max_models, and an update_model_handler call made while the key is loading gets lost, so the old model is kept.

So I kept reserving the tag before the load and covered the points you raised:

  • self._mh_map[key] is looked up before the tag is reserved, so an unknown key leaves nothing in _tag_map.
  • The rollback catches BaseException and only removes the tag if it still belongs to this call.
  • Eviction and update_model_handler now go through _release_tag, which skips a model that's still loading instead of raising KeyError on _proxy_map[tag]. When that load finishes, load() sees its tag was removed and releases the model instead of keeping it.
  • I used your max_models == 0 guard, so a new key never evicts itself.

I added tests for each of these, including two threads loading the same key and evicting or updating a model while it's loading. I also merged master to fix the conflict. If you'd still prefer the deferred insert, I'm happy to switch to it.

@damccorm

Copy link
Copy Markdown
Contributor

Also, please resolve the conflicts. Otherwise, this LGTM

Comment on lines +736 to +741
if self._tag_map.get(key) == tag:
self._proxy_map[tag] = (shared_handle, model_reference)
else:
# The model was evicted or updated while it was loading, so don't keep
# a reference to it.
shared_handle.release(model_reference)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Good catch on preserving shared in-flight loads — keeping the tag reservation before acquire() makes sense.

Since _ModelHandlerManager serves concurrent calls across threads (and already uses self._max_models_lock for that reason), could we also guard the short _tag_map / _proxy_map / _mh_map reads & updates with a lock (releasing the lock before calling shared_handle.acquire() and shared_handle.release())? Without a lock, there are still a few narrow TOCTOU races:

  • Between if self._tag_map.get(key) == tag: and self._proxy_map[tag] = (shared_handle, model_reference): if another thread evicts or updates key in that window, _release_tag(tag) pops None and load() then inserts tag into _proxy_map with no _tag_map entry, leaking the model reference.
  • Between if key in self._tag_map: and move_to_end(key) / _tag_map[key] in load() (or self._tag_map.pop(key) in update_model_handler), a concurrent eviction/update can raise KeyError.
  • Two threads hitting a cold load(same_key) before _tag_map[key] = tag can both miss and double-load (and concurrent loads of different keys can overshoot _max_models).

Reusing self._max_models_lock (e.g., as self._lock) for the in-memory dict/LRU state and doing acquire() / release() outside the lock keeps shared in-flight loads intact with no deadlock risk and closes all of these cleanly.

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.

Thanks, done. All map and counter reads and writes now happen under _lock, and acquire() and release() always run outside it, so concurrent loads of the same key still share one model.

@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.72727% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 58.05%. Comparing base (a5daa5e) to head (1c62ee9).
⚠️ Report is 9 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/ml/inference/base.py 97.72% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##             master   #41405   +/-   ##
=========================================
  Coverage     58.05%   58.05%           
  Complexity     2842     2842           
=========================================
  Files          1210     1210           
  Lines        173310   173339   +29     
  Branches       2329     2329           
=========================================
+ Hits         100617   100635   +18     
- Misses        69978    69989   +11     
  Partials       2715     2715           
Flag Coverage Δ
python 80.68% <97.72%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions github-actions Bot added Next Action: Reviewers size/m M: 50-249 lines changed and removed Next Action: Author size/s S: 10-49 lines changed labels Nov 25, 2026

@damccorm damccorm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks - I'll merge once checks pass

@damccorm
damccorm merged commit 6daff1a into apache:master Nov 25, 2026
89 of 91 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Multi-model KeyedModelHandler reloads a model on every batch after one failed load_model call

2 participants