AmoghAtreya commented on code in PR #40765:
URL: https://github.com/apache/beam/pull/40765#discussion_r4674914547


##########
sdks/python/apache_beam/ml/inference/utils.py:
##########
@@ -68,54 +74,122 @@ def _convert_to_result(
   return results
 
 
-class _ConvertIterToSingleton(beam.DoFn):
-  """
-  Internal only; No backwards compatibility.
-
-  The MatchContinuously transform examines all files present in a given
-  directory and returns those that have timestamps older than the
-  pipeline's start time. This can produce an Iterable rather than a
-  Singleton. This class only returns the file path when it is first
-  encountered, and it is cached as part of the side input caching mechanism.
-  If the path is seen again, it will not return anything.
-  By doing this, we can ensure that the output of this transform can be wrapped
-  with beam.pvalue.AsSingleton().
+def _as_seconds(timestamp: Union[Timestamp, float]) -> float:
+  return float(timestamp)
+
+
+def _is_newer(
+    candidate: Optional[FileMetadata],
+    incumbent: Optional[FileMetadata]) -> bool:
+  """Return true when candidate should replace incumbent as the latest file.
+
+  The newest modification time wins. Equal timestamps are broken by path so
+  the choice is the same no matter which order the files are merged in.
   """
-  COUNT_STATE = CombiningValueStateSpec('count', combine_fn=sum)
+  if candidate is None:
+    return False
+  if incumbent is None:
+    return True
+  candidate_ts = _as_seconds(candidate.last_updated_in_seconds)
+  incumbent_ts = _as_seconds(incumbent.last_updated_in_seconds)
+  if candidate_ts != incumbent_ts:
+    return candidate_ts > incumbent_ts
+  return candidate.path > incumbent.path
+
+
+def _with_global_key(metadata: FileMetadata):
+  return _GLOBAL_MODEL_KEY, metadata
 
-  def process(self, element, count_state=beam.DoFn.StateParam(COUNT_STATE)):
-    counter = count_state.read()
-    if counter == 0:
-      count_state.add(1)
-      yield element[1]
 
+def _model_metadata(path: str) -> ModelMetadata:
+  model_name = os.path.splitext(os.path.basename(path))[0]
+  return ModelMetadata(model_id=path, model_name=model_name)
 
-class _GetLatestFileByTimeStamp(beam.DoFn):
+
+class _LatestFileCombineFn(beam.CombineFn):
+  """Selects the FileMetadata with the newest modification time.
+
+  Internal only; no backwards compatibility.
   """
-  Internal only; No backwards compatibility.
+  def create_accumulator(self):
+    return None
+
+  def add_input(self, accumulator, element):
+    if _is_newer(element, accumulator):
+      return element
+    return accumulator
+
+  def merge_accumulators(self, accumulators):
+    merged = None
+    for accumulator in accumulators:
+      if _is_newer(accumulator, merged):
+        merged = accumulator
+    return merged
+
+  def extract_output(self, accumulator):
+    return accumulator
+
 
-  This DoFn checks the timestamps of files against the time that the pipeline
-  began running. It returns the files that were modified after the pipeline
-  started. If no such files are found, it returns a default file as fallback.
-   """
-  TIME_STATE = CombiningValueStateSpec(
-      'max', combine_fn=partial(max, default=_START_TIME_STAMP))
+class _EmitLatestModel(beam.DoFn):
+  """Emits a model only when it is newer than every model seen so far.
 
-  def process(self, element, time_state=beam.DoFn.StateParam(TIME_STATE)):
+  Internal only; no backwards compatibility.
+
+  Input is ``(key, FileMetadata)`` and every file shares one key, so this
+  state is the newest timestamp across the whole watch, not per path. The
+  first time the newest file is at or before pipeline construction, one
+  ``ModelMetadata(model_id='')`` is emitted so a streaming side input is
+  available and ``RunInference`` uses the model configured on the handler.
+  A later file is emitted only when it is newer than that. Emitting at most
+  one value per pane keeps the output usable as a singleton side input.
+  """
+  LATEST_TS = ReadModifyWriteStateSpec('latest_ts', FloatCoder())
+
+  def process(self, element, latest_ts=beam.DoFn.StateParam(LATEST_TS)):
     _, file_metadata = element
-    new_ts = file_metadata.last_updated_in_seconds
-    old_ts = time_state.read()
-    if new_ts > old_ts:
-      time_state.clear()
-      time_state.add(new_ts)
-      model_path = file_metadata.path
-    else:
-      model_path = ''
-
-    model_name = os.path.splitext(os.path.basename(model_path))[0]
-    return [
-        (model_path, ModelMetadata(model_id=model_path, model_name=model_name))
-    ]
+    if file_metadata is None:
+      return
+    new_ts = _as_seconds(file_metadata.last_updated_in_seconds)
+    start_ts = _as_seconds(_START_TIME_STAMP)

Review Comment:
   Done. WatchFilePattern records the construction time in __init__ and stores 
it on _EmitLatestModel as self._start_ts, so that value is serialized with the 
pipeline. process() compares file timestamps with that saved time. A model 
uploaded after submission and before a worker starts is treated as a new model. 
Tests pass an explicit start time, and one checks that the DoFn in the pipeline 
graph still has the construction time after pickling.



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