damccorm commented on code in PR #40765:
URL: https://github.com/apache/beam/pull/40765#discussion_r4672276101
##########
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:
Reading the module-level `_START_TIME_STAMP` dynamically inside `process()`
means that on distributed runners (e.g., Dataflow/Flink/Spark), `start_ts` is
evaluated to when each worker imports `utils.py` (often minutes after job
submission during worker startup) rather than pipeline construction time.
Previously, `CombiningValueStateSpec(..., combine_fn=partial(max,
default=_START_TIME_STAMP))` captured the submission-time value inside the
serialized `partial`.
If a model is uploaded between pipeline submission and worker boot, `new_ts
<= start_ts` will be true on the worker, treating it as a pre-start file
(emitting `model_id=''`) and seeding `LATEST_TS` with the later worker import
time so that model is ignored.
Could we capture `start_timestamp` in `WatchFilePattern.__init__` /
`_SelectLatestModel.__init__` / `_EmitLatestModel.__init__` (defaulting to
`Timestamp.now()`) and store `self._start_ts = _as_seconds(start_timestamp)` on
the `DoFn` instance so it is serialized with the pipeline? That would also
match the docstring ("at or before pipeline construction") and make tests
easier to parameterize without relying on module-level `_START_TIME_STAMP`.
##########
CHANGES.md:
##########
@@ -224,6 +224,7 @@
## Bugfixes
* (Python) Fixed timestamp and side-input argument binding when a
`DoFn.process` or `DoFn.process_batch` method gives its element or batch
parameter a default value
([#19631](https://github.com/apache/beam/issues/19631)).
+* (Python) Fixed `WatchFilePattern` comparing model files only against their
own path, so an older model could be chosen and a poll that saw several models
could crash `RunInference` (`AsSingleton` requires one value)
([#40638](https://github.com/apache/beam/issues/40638)).
Review Comment:
2.78.0 has already been released—could you move this entry up to the `#
[2.79.0] - Unreleased` section once rebased/merged with `master`?
##########
sdks/python/apache_beam/ml/inference/utils_test.py:
##########
@@ -26,82 +26,130 @@
from apache_beam.ml.inference.base import ModelHandler
from apache_beam.ml.inference.base import PredictionResult
from apache_beam.ml.inference.base import RunInference
+from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.testing.test_pipeline import TestPipeline
+from apache_beam.testing.test_stream import TestStream
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
+def _file(path, seconds_from_start):
+ return FileMetadata(
+ path,
+ 10,
+ last_updated_in_seconds=utils._START_TIME_STAMP + seconds_from_start)
+
+
+def _model_ids(pcoll, label='ModelIds'):
+ return pcoll | label >> beam.Map(lambda model: model.model_id)
+
+
class WatchFilePatternTest(unittest.TestCase):
- def test_latest_file_by_timestamp_default_value(self):
- # match continuously returns the files in sorted timestamp order.
- main_input_pcoll = [
- FileMetadata(
- 'path1.py',
- 10,
- last_updated_in_seconds=utils._START_TIME_STAMP - 20),
- FileMetadata(
- 'path2.py',
- 10,
- last_updated_in_seconds=utils._START_TIME_STAMP - 10)
- ]
+ def test_latest_file_combine_fn_picks_newest_regardless_of_order(self):
+ older = _file('older.py', 10)
+ newer = _file('newer.py', 50)
+ initial = _file('initial.py', -5)
+ combine = utils._LatestFileCombineFn()
+
+ def accumulate(files):
+ accumulator = combine.create_accumulator()
+ for metadata in files:
+ accumulator = combine.add_input(accumulator, metadata)
+ return accumulator
+
+ merged = combine.merge_accumulators(
+ [accumulate([older]), accumulate([newer, initial])])
+ self.assertEqual('newer.py', combine.extract_output(merged).path)
+ swapped = combine.merge_accumulators(
+ [accumulate([newer, initial]), accumulate([older])])
+ self.assertEqual('newer.py', combine.extract_output(swapped).path)
+
+ def test_latest_file_combine_fn_breaks_timestamp_ties_by_path(self):
+ combine = utils._LatestFileCombineFn()
+ first = combine.add_input(combine.create_accumulator(), _file('b.py', 10))
+ second = combine.add_input(combine.create_accumulator(), _file('a.py', 10))
+ merged = combine.merge_accumulators([first, second])
+ self.assertEqual('b.py', combine.extract_output(merged).path)
+
+ def test_files_at_or_before_pipeline_start_emit_configured_model_once(self):
+ # Several pre-start files are one poll. They publish the configured model
+ # once (an empty model id), not one value per file.
+ files = [_file('path1.py', -20), _file('path2.py', -10), _file('now.py',
0)]
+ with TestPipeline() as p:
+ emitted = _model_ids(p | beam.Create(files) | utils._SelectLatestModel())
+ assert_that(emitted, equal_to(['']))
+
+ def test_configured_model_then_a_newer_file(self):
+ files = [_file('initial.py', -5), _file('newer.py', 50)]
with TestPipeline() as p:
- files_pc = (
+ emitted = _model_ids(
p
- | beam.Create(main_input_pcoll)
- | beam.Map(lambda x: (x.path, x))
- | beam.ParDo(utils._GetLatestFileByTimeStamp())
- | beam.Map(lambda x: x[0]))
- assert_that(files_pc, equal_to(['', '']))
-
- def test_latest_file_with_timestamp_after_pipeline_construction_time(self):
- main_input_pcoll = [
- FileMetadata(
- 'path1.py',
- 10,
- last_updated_in_seconds=utils._START_TIME_STAMP + 10)
+ | beam.Create(files)
+ | beam.Map(lambda metadata: (utils._GLOBAL_MODEL_KEY, metadata))
+ | beam.ParDo(utils._EmitLatestModel()),
+ label='ConfiguredThenUpdated')
+ assert_that(emitted, equal_to(['', 'newer.py']))
+
+ def test_file_newer_than_pipeline_start_is_emitted(self):
+ with TestPipeline() as p:
+ emitted = _model_ids(
+ p | beam.Create([_file('path1.py', 10)]) |
utils._SelectLatestModel())
+ assert_that(emitted, equal_to(['path1.py']))
+
+ def test_one_poll_emits_only_the_newest_model(self):
+ # Newest file is not last, and another post-start file is present, so
+ # neither input order nor "every new path" can select the right model.
+ files = [
+ _file('path4.py', 20),
+ _file('path1.py', -20),
+ _file('path3.py', 10),
+ _file('path2.py', -10),
]
with TestPipeline() as p:
- files_pc = (
+ updates = p | 'Files' >> beam.Create(files) | utils._SelectLatestModel()
+ assert_that(_model_ids(updates), equal_to(['path4.py']), label='emitted')
+ singleton = (
p
- | beam.Create(main_input_pcoll)
- | beam.Map(lambda x: (x.path, x))
- | beam.ParDo(utils._GetLatestFileByTimeStamp())
- | beam.Map(lambda x: x[0]))
- assert_that(files_pc, equal_to(['path1.py']))
-
- def test_emitting_singleton_output(self):
- # match continuously returns the files in sorted timestamp order.
- main_input_pcoll = [
- FileMetadata(
- 'path1.py',
- 10,
- last_updated_in_seconds=utils._START_TIME_STAMP - 20),
- # returns default
- FileMetadata(
- 'path2.py',
- 10,
- last_updated_in_seconds=utils._START_TIME_STAMP - 10),
- # returns default
- FileMetadata(
- 'path3.py',
- 10,
- last_updated_in_seconds=utils._START_TIME_STAMP + 10),
- FileMetadata(
- 'path4.py',
- 10,
- last_updated_in_seconds=utils._START_TIME_STAMP + 20)
- ]
- # returns path3.py
+ | 'Probe' >> beam.Create([None])
+ | beam.Map(
+ lambda _, model: model.model_id,
+ beam.pvalue.AsSingleton(updates)))
+ assert_that(singleton, equal_to(['path4.py']), label='singleton')
+
+ def test_older_update_does_not_replace_a_newer_model(self):
+ # Shared key, processed in input order. The second file is still newer
+ # than pipeline start, but older than the model already accepted.
+ files = [_file('newer.py', 50), _file('older.py', 10)]
+ with TestPipeline() as p:
+ emitted = _model_ids(
+ p
+ | beam.Create(files)
+ | beam.Map(lambda metadata: (utils._GLOBAL_MODEL_KEY, metadata))
+ | beam.ParDo(utils._EmitLatestModel()))
+ assert_that(emitted, equal_to(['newer.py']))
+ def test_newer_update_replaces_an_older_model(self):
+ files = [_file('older.py', 10), _file('newer.py', 50)]
with TestPipeline() as p:
- files_pc = (
+ emitted = _model_ids(
p
- | beam.Create(main_input_pcoll)
- | beam.Map(lambda x: (x.path, x))
- | beam.ParDo(utils._GetLatestFileByTimeStamp())
- | beam.ParDo(utils._ConvertIterToSingleton())
- | beam.Map(lambda x: x[0]))
- assert_that(files_pc, equal_to(['', 'path3.py', 'path4.py']))
+ | beam.Create(files)
+ | beam.Map(lambda metadata: (utils._GLOBAL_MODEL_KEY, metadata))
+ | beam.ParDo(utils._EmitLatestModel()),
+ label='UpdatedModelIds')
+ assert_that(emitted, equal_to(['older.py', 'newer.py']))
+
+ def test_later_poll_does_not_emit_an_older_model(self):
+ options = PipelineOptions(flags=['--streaming'])
+ with TestPipeline(options=options) as p:
+ stream = (
+ TestStream().advance_watermark_to(0).add_elements(
+ [_file('newer.py',
50)]).advance_processing_time(5).add_elements([
+ _file('older.py', 10)
+ ]).advance_processing_time(5).advance_watermark_to_infinity())
+ emitted = _model_ids(
+ p | stream | utils._SelectLatestModel(), label='PolledModelIds')
+ assert_that(emitted, equal_to(['newer.py']))
Review Comment:
Since this test only expects a single element (`['newer.py']`), it would
still pass even if `AfterProcessingTime(1)` never fired early and
`CombinePerKey` combined both elements into one pane at
`advance_watermark_to_infinity()`. Meanwhile, the tests above that check
multi-step state transitions (`test_configured_model_then_a_newer_file`,
`test_older_update_does_not_replace_a_newer_model`,
`test_newer_update_replaces_an_older_model`) bypass `_SelectLatestModel` and
rely on `beam.Create` preserving list order, which isn't guaranteed by the Beam
model.
Could we add (or expand this into) a `TestStream` test through
`_SelectLatestModel()` that produces multiple outputs across processing-time
advances—for example: pre-start files -> `''`, a newer file -> `'v1.py'`, a
stale file -> dropped, and multiple newer files in one poll -> only `'v2.py'`
(asserting `equal_to(['', 'v1.py', 'v2.py'])`)? That would verify early
triggering, per-pane reduction, initial `''` emission, and cross-poll state
persistence end-to-end.
--
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]