damccorm commented on code in PR #41569:
URL: https://github.com/apache/beam/pull/41569#discussion_r4670675572
##########
sdks/python/apache_beam/io/filebasedsink.py:
##########
@@ -252,14 +273,16 @@ def _get_final_name_glob(self, num_shards, w=None):
window_utc = (
'[' + w.start.to_utc_datetime().strftime("%Y-%m-%dT%H-%M-%S") + ', '
+
w.end.to_utc_datetime().strftime("%Y-%m-%dT%H-%M-%S") + ')')
+ # Only the shard name part is a glob. The prefix and suffix must match
+ # literally, or pre_finalize could delete unrelated files.
return ''.join([
- self.file_path_prefix.get(),
+ _escape_glob(self.file_path_prefix.get()),
self.shard_name_glob_format % dict(
num_shards=num_shards,
uuid=(uuid.uuid4()),
window=w,
window_utc=window_utc),
- self.file_name_suffix.get()
+ _escape_glob(self.file_name_suffix.get())
])
Review Comment:
Minor: `_check_state_for_finalize_write` passes `dst_glob` to
`self._report_sink_lineage(dst_glob, dst_files)`. When `len(dst_files) <= 10`
it reports the unescaped `dst_files` (`out[12]-00000-of-00002.output`), whereas
when `len(dst_files) > 10` it reports `dst_glob`, which will now record
`out[[]12]-*-of-00020.output` in the lineage FQN. Might be worth keeping an
unescaped glob (or unescaping) for `_report_sink_lineage` so both branches are
consistent.
##########
sdks/python/apache_beam/io/filebasedsink.py:
##########
@@ -45,6 +45,27 @@
_LOGGER = logging.getLogger(__name__)
+def _escape_glob(path):
+ """Returns a pattern that matches only `path`, even if it contains
+ the glob characters `*`, `?` or `[`."""
+ return re.sub(r'([*?[])', r'[\1]', path)
Review Comment:
Two small things here:
1. Could we use stdlib `glob.escape(path)` instead of `re.sub`? It escapes
the same `[*?[]` set, and also runs `os.path.splitdrive` first so Windows
extended-length prefixes like `\\?\C:\...` don't get turned into `\\[?]\C:\...`.
2. Passing `[[]` into `FileSystem.translate_pattern()` (`filesystem.py:698`,
which was ported from Python 2.7's `fnmatch.translate`) produces unescaped
`[[]` in the regex, which triggers `FutureWarning: Possible nested set` in
`re.compile` on Python 3.7+. If we escape `[` (and `&`, `~`, `|`) inside
character classes in `translate_pattern` the way Python 3's `fnmatch.translate`
does (e.g. `stuff = re.sub(r'([&~|\[])', r'\\\1', stuff)`), we avoid emitting
`FutureWarning`s.
##########
sdks/python/apache_beam/io/filebasedsink.py:
##########
@@ -45,6 +45,27 @@
_LOGGER = logging.getLogger(__name__)
+def _escape_glob(path):
+ """Returns a pattern that matches only `path`, even if it contains
+ the glob characters `*`, `?` or `[`."""
+ return re.sub(r'([*?[])', r'[\1]', path)
+
+
+def _delete_literal(paths):
+ """Deletes the exact `paths`.
+
+ The local and GCS file systems treat the paths they delete as patterns, so
+ glob characters in a path are escaped for them. The others delete paths
+ as they are.
+ """
+ def literal(path):
+ if FileSystems.get_scheme(path) in (None, 'gs'):
+ return _escape_glob(path)
+ return path
+
+ FileSystems.delete([literal(path) for path in paths])
Review Comment:
In `FileSystem.match()` (`filesystem.py:742`), `prefix_or_dir =
re.match('^[^[*?]*', pattern).group(0)` truncates at the first `[` even when
it's an escaped literal like `[[]`, `[*]`, or `[?]`. That causes a couple of
issues:
1. **Repeated prefix/directory scans in `_delete_literal`:** Normally,
passing literal paths to `GCSFileSystem.delete()` or `LocalFileSystem.delete()`
hits the `if prefix_or_dir == pattern:` short-circuit (`self.exists(pattern)`).
Once `[` is escaped to `[[]`, `prefix_or_dir != pattern`, so `delete()` skips
the short-circuit and runs `self._list(prefix_or_dir)` once per shard in
`paths` (e.g. overwriting `N` shards at `gs://bucket/run[1]/deep/path/out` runs
`N` full `list_blobs(prefix='run')` scans; `/tmp/run[1]/out` runs
`os.walk('/tmp')` per shard).
2. **`HadoopFileSystem` (`hdfs://`):** `_create_temp_dir` embeds the prefix
basename in `beam-temp-out[12]-<uuid>`, so `src_glob`
(`hdfs:///dir/beam-temp-out[[]12]-<uuid>/*`) gets its `prefix_or_dir` stripped
to `hdfs:///dir`. Since `HadoopFileSystem._list()` is non-recursive
(`has_dirs() == True`), it only lists `/dir` instead of the temp dir and
finalize still fails with `BeamIOError: src and dst files do not exist`.
If we update `FileSystem.match()` to treat `\[[*?[]\]` as literal characters
when extracting `prefix_or_dir`:
```python
prefix_match = re.match(r'^(?:[^[*?]|\[[*?[]\])*', pattern).group(0)
prefix_or_dir = re.sub(r'\[([*?[])\]', r'\1', prefix_match)
file_metadatas = []
if prefix_match == pattern:
if self.exists(prefix_or_dir):
file_metadatas = [self.metadata(prefix_or_dir)]
```
that avoids the `O(N)` list scans in `_delete_literal`, keeps the full
directory prefix for HDFS/local/GCS `match()` calls, and would also let
`_delete_literal([init_result])` at the end of `finalize_windowed_write` clean
up the empty `beam-temp-*` directory on `LocalFileSystem`.
--
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]