#3387·metaflow

Local metadata write failures surface as UnboundLocalError instead of the OSError that names the path

Author: kevin9327Created Sep 26, 2026Updated Sep 26, 2026

Summary

When the local metadata provider cannot create the temp file it writes through, the user sees UnboundLocalError: cannot access local variable 'f' where it is not associated with a value raised from inside Metaflow, instead of the PermissionError or FileNotFoundError that names the path that could not be written.

Runtime

Local (--metadata local, the default). LocalMetadataProvider._dump_json_to_file is on the hot path of every local run: _save_meta calls it for register_run_id, register_task_id, register_metadata and register_data_artifacts. Any failure to create the temp file (unwritable .metaflow directory, read-only mount, directory removed underneath the run) takes this path.

Reproduction

python
import os, tempfile
from metaflow.plugins.metadata_providers.local import LocalMetadataProvider

base = tempfile.mkdtemp()
target = os.path.join(base, "not_created_yet", "_self.json")
try:
    LocalMetadataProvider._dump_json_to_file(target, {"a": 1})
except Exception as e:
    print("RAISED: %s -> %s" % (type(e).__name__, e))

Observed on master:

RAISED: UnboundLocalError -> cannot access local variable 'f' where it is not associated with a value

Expected

The original OSError propagates:

RAISED: FileNotFoundError -> [Errno 2] No such file or directory: '.../not_created_yet/tmpec4e4v07'

Cause

In metaflow/plugins/metadata_providers/local.py, _dump_json_to_file binds f with a with tempfile.NamedTemporaryFile(...) as f: statement inside a try, and its finally clause evaluates if f and os.path.isfile(f.name). When the NamedTemporaryFile call itself raises, f was never assigned, so the cleanup raises UnboundLocalError while the original OSError is propagating, and that replaces it as the visible error.

Fix proposed in #3369 (bind f = None before the try, which the cleanup condition already tolerates).