damccorm commented on code in PR #41405:
URL: https://github.com/apache/beam/pull/41405#discussion_r4698383176


##########
sdks/python/apache_beam/ml/inference/base.py:
##########
@@ -707,26 +707,38 @@ def load(self, key: str) -> _ModelLoadStats:
     if key in self._tag_map:
       self._tag_map.move_to_end(key)
       return _ModelLoadStats(self._tag_map[key], None, None)
-    else:
-      self._tag_map[key] = uuid.uuid4().hex
 
-    tag = self._tag_map[key]
     mh = self._mh_map[key]
+    tag = uuid.uuid4().hex
+    # Reserve the tag before loading the model, so that a concurrent load(key)
+    # returns this tag and shares this model instead of loading another copy.
+    self._tag_map[key] = tag
 
-    if self._max_models is not None and self._max_models < len(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]
+    if (self._max_models is not None and
+        len(self._tag_map) > max(self._max_models, 1)):
+      # If we're about to exceed our LRU size, release the least recently used
+      # model. The new key is the most recently used one, so it is kept.
+      self._release_tag(self._tag_map.popitem(last=False)[1])
 
     # 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._proxy_map[tag] = (shared_handle, model_reference)
+    try:
+      model_reference = shared_handle.acquire()
+    except BaseException:
+      # Forget the tag so that the next call loads the model again instead of
+      # returning a tag that has no model behind it.
+      if self._tag_map.get(key) == tag:
+        del self._tag_map[key]
+      raise
+    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)

Review Comment:
   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.



##########
sdks/python/apache_beam/ml/inference/base_test.py:
##########
@@ -2189,6 +2210,122 @@ def 
test_model_handler_manager_increments_once_per_process(self):
     mm.load('key1')
     self.assertEqual(['key3', 'key1'], list(mm._tag_map.keys()))
 
+  def test_model_handler_manager_retries_failed_load(self):
+    # state=100 makes FakeStatefulModel raise when the model is loaded.
+    mh1 = FakeModelHandler(state=100)
+    mh2 = FakeModelHandler(state=2)
+    mm = base._ModelHandlerManager(mh_map={'key1': mh1, 'key2': mh2})
+    mm.increment_max_models(1)
+    with self.assertRaisesRegex(Exception, 'Oh no'):
+      mm.load('key1')
+    self.assertEqual([], list(mm._tag_map.keys()))
+
+    # The next load of key1 loads the model again and keeps it.
+    mh1._state = 1
+    stats = mm.load('key1')
+    self.assertIsNotNone(stats.load_latency)
+    # Use bad_mh's load function to make sure the model is already stored.
+    bad_mh = FakeModelHandler(state=100)
+    model1 = multi_process_shared.MultiProcessShared(
+        bad_mh.load_model, tag=stats.model_tag).acquire()
+    self.assertEqual(1, model1.predict(10))
+    self.assertIsNone(mm.load('key1').load_latency)
+
+    # Evicting key1 to load key2 works.
+    mm.load('key2')
+    self.assertEqual(['key2'], list(mm._tag_map.keys()))
+
+  def test_model_handler_manager_unknown_key_leaves_no_tag(self):
+    mm = base._ModelHandlerManager(mh_map={'key1': FakeModelHandler(state=1)})
+    with self.assertRaises(KeyError):
+      mm.load('missing')
+    self.assertEqual([], list(mm._tag_map.keys()))
+
+  def test_model_handler_manager_with_max_models_zero_keeps_new_model(self):
+    mm = base._ModelHandlerManager(
+        mh_map={
+            'key1': FakeModelHandler(state=1),
+            'key2': FakeModelHandler(state=2)
+        })
+    mm.increment_max_models(0)
+    tag1 = mm.load('key1').model_tag
+    self.assertEqual({'key1': tag1}, dict(mm._tag_map))
+    self.assertEqual([tag1], list(mm._proxy_map.keys()))
+    tag2 = mm.load('key2').model_tag
+    self.assertEqual({'key2': tag2}, dict(mm._tag_map))
+    self.assertEqual([tag2], list(mm._proxy_map.keys()))
+
+  def _start_blocking_load(self, mm, key):
+    """Starts mm.load(key) on a thread and waits until load_model runs."""
+    mh = mm._mh_map[key]
+    results = []
+    thread = threading.Thread(target=lambda: results.append(mm.load(key)))
+    thread.start()

Review Comment:
   Nit: adding `self.addCleanup(mh.finish_load.set)` here ensures a failing 
assertion in any of the blocking tests won't leave a non-daemon worker thread 
blocked for the full 60s timeout.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to