Repository navigation
fix(studio): reject ambiguous S3 audio references - #16529
Conversation
|
Please allow maintainers to edit this pull request |
Lyxot
left a comment
There was a problem hiding this comment.
Thanks for the fix and the thorough repro. Rejecting the ambiguity, rather than reversing precedence, is the right call: #10050 shipped prefix-relative-first, so flipping it would silently re-pair datasets that rely on it. Comparing candidates by their resolved local path (one per key) is reliable and costs no extra S3 requests.
I couldn't push to the branch because "Allow edits by maintainers" is off, so here is the follow-up I'd like folded in. The patch is below and applies on top of 3a2e5ce.
1. Fail before downloading the audio. The ambiguity check runs in _rewrite_audio_references, which currently runs after every audio file has downloaded. On a large dataset the user waits for the whole download (and, on the GPU path, the concurrent model-weight prefetch) only to get the error. Rewriting needs only the key -> local path map, which is deterministic, so the patch splits _download_structured into _structured_local_paths (map and traversal guard) and a download loop. It then downloads the manifests, rewrites, and only then downloads the audio. Any rewrite error now fails right after the manifest download, and the test asserts that only the manifest was fetched when a reference is ambiguous.
2. Drop the ./ and s3:// early returns. Neither ever changes the result. Lookup keys never start with ./, so direct is always None for those values and the final line already returns relative. An s3:// value can never match a manifest-relative key, so relative is always None and the final line returns direct.
Validation: tests/test_s3_audio_dataset.py and tests/test_s3_dataset.py pass (59). Each of these mutations fails the new tests: removing the refusal, refusing whenever both candidates exist, and rewriting after the audio download.
Patch
diff --git a/studio/backend/core/training/s3_dataset.py b/studio/backend/core/training/s3_dataset.py
index 9beb530b0dd..c2de23c3fad 100644
--- a/studio/backend/core/training/s3_dataset.py
+++ b/studio/backend/core/training/s3_dataset.py
@@ -189,13 +189,12 @@ def _key_relative_to_prefix(key: str, prefix: Optional[str]) -> str:
return key.lstrip("/")
-def _download_structured(
- client, bucket: str, prefix: Optional[str], keys: list[str], target_dir: str, cancel_callback
+def _structured_local_paths(
+ prefix: Optional[str], keys: list[str], target_dir: str
) -> dict[str, str]:
- """Download ``keys`` mirroring their prefix-relative layout. Returns key -> local path."""
+ """Map ``keys`` to local paths mirroring their prefix-relative layout."""
local_by_key: dict[str, str] = {}
for key in keys:
- _raise_if_cancelled(cancel_callback)
relative = _key_relative_to_prefix(key, prefix)
parts = [part for part in relative.split("/") if part not in ("", ".")]
# ".." is a legal S3 key segment: refuse rather than write above target_dir.
@@ -204,21 +203,26 @@ def _download_structured(
f"S3 key {key!r} contains '..' or empty path segments and cannot "
"be downloaded into the dataset directory."
)
- local_path = _contained_local_path(target_dir, parts)
- os.makedirs(os.path.dirname(local_path) or target_dir, exist_ok = True)
- _download_one(client, bucket, key, local_path, cancel_callback)
- local_by_key[key] = local_path
+ local_by_key[key] = _contained_local_path(target_dir, parts)
return local_by_key
+def _download_structured(client, bucket: str, local_by_key: dict[str, str], cancel_callback):
+ for key, local_path in local_by_key.items():
+ _raise_if_cancelled(cancel_callback)
+ os.makedirs(os.path.dirname(local_path), exist_ok = True)
+ _download_one(client, bucket, key, local_path, cancel_callback)
+
+
def _rewrite_audio_references(
manifest_local_by_key: dict[str, str],
audio_local_by_key: dict[str, str],
bucket: str,
prefix: Optional[str],
) -> None:
- """Rewrite audio values naming a downloaded key (prefix-relative, ``s3://`` URI, or
- manifest-relative) to its local path; anything else is left as written."""
+ """Rewrite audio values naming an audio key (prefix-relative, ``s3://`` URI, or
+ manifest-relative) to its local path; anything else is left as written. A value whose
+ prefix- and manifest-relative readings name different keys is refused."""
lookup: dict[str, str] = {}
for key, local_path in audio_local_by_key.items():
lookup[_key_relative_to_prefix(key, prefix)] = local_path
@@ -233,12 +237,8 @@ def _rewrite_audio_references(
if not isinstance(value, str) or not value.lower().endswith(_AUDIO_EXTENSIONS):
return None
direct = lookup.get(value)
- if value.startswith("s3://"):
- return direct
relative_to_manifest = os.path.normpath(os.path.join(manifest_dir, value))
relative = lookup.get(relative_to_manifest.replace(os.sep, "/"))
- if value.startswith("./"):
- return relative
if direct is not None and relative is not None and direct != relative:
raise ValueError(
f"Ambiguous audio reference {value!r} in S3 manifest {manifest_key!r}: "
@@ -366,14 +366,13 @@ def prepare_s3_dataset_download(
local_files: list[str] = []
if audio_keys:
- manifest_local_by_key = _download_structured(
- client, bucket, prefix, keys, target_dir, cancel_callback
- )
- audio_local_by_key = _download_structured(
- client, bucket, prefix, audio_keys, target_dir, cancel_callback
- )
- local_files = list(manifest_local_by_key.values())
+ manifest_local_by_key = _structured_local_paths(prefix, keys, target_dir)
+ audio_local_by_key = _structured_local_paths(prefix, audio_keys, target_dir)
+ _download_structured(client, bucket, manifest_local_by_key, cancel_callback)
+ # Rewrite before the audio download so a bad manifest fails without fetching it.
_rewrite_audio_references(manifest_local_by_key, audio_local_by_key, bucket, prefix)
+ _download_structured(client, bucket, audio_local_by_key, cancel_callback)
+ local_files = list(manifest_local_by_key.values())
else:
used_paths: set[str] = set()
for key in keys:
diff --git a/studio/backend/tests/test_s3_audio_dataset.py b/studio/backend/tests/test_s3_audio_dataset.py
index 5b57f9d9018..25eb96fb76c 100644
--- a/studio/backend/tests/test_s3_audio_dataset.py
+++ b/studio/backend/tests/test_s3_audio_dataset.py
@@ -224,7 +224,7 @@ def test_audio_reference_ambiguity(
keys.append("datasets/clips/a.wav")
if nested_audio:
keys.append("datasets/train/clips/a.wav")
- _install(monkeypatch, keys, contents = {manifest_key: content})
+ client = _install(monkeypatch, keys, contents = {manifest_key: content})
if expected is None:
with pytest.raises(ValueError, match = "Ambiguous audio reference") as error:
@@ -233,6 +233,7 @@ def test_audio_reference_ambiguity(
assert manifest_key in str(error.value)
assert "./" in str(error.value) and "s3://" in str(error.value)
assert (tmp_path / "train" / ("rows" + suffix)).read_text() == content
+ assert [key for _, key, _ in client.downloaded] == [manifest_key]
return
files = s3_dataset.download_s3_dataset(_cfg(), dest_dir = str(tmp_path))Co-authored-by: Lyxot <[email protected]>
|
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Review workflow done on
|
Lyxot
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the fix and for folding in the follow-up.
A manifest-relative audio path can silently select a different recording when the selected S3 prefix also contains that path, leaving its transcript paired with the wrong audio.
Reject references whose prefix-relative and manifest-relative candidates identify different files. Compute the local path maps first, download and validate the manifests, and download audio only after validation succeeds. The error identifies the manifest and reference and explains how to disambiguate with
./or a fulls3://URI. Unambiguous and unmatched references retain their behavior; ambiguous inputs are rejected rather than changing path precedence.Fixes #16528.
Validation:
python -m pytest studio/backend/tests/test_s3_audio_dataset.py studio/backend/tests/test_s3_dataset.py -q --tb=short: 59 passed.scripts/run_ruff_format.py, scoped Ruff 0.16.10, andgit diff --checkpass.Only the S3 dataset loader and its existing test module change. Validated on macOS arm64 / Python 3.13.5; no live AWS or GPU training run.