Skip to content

fix: delete objects by path in writable directories - #1850

Open
lyn1dev wants to merge 2 commits into
scikit-hep:mainfrom
lyn1dev:fix_delete-key-by-path
Open

lyn1dev wants to merge 2 commits into
scikit-hep:mainfrom
lyn1dev:fix_delete-key-by-path

Conversation

@lyn1dev

@lyn1dev lyn1dev commented Nov 22, 2026 •

Copy link
Copy Markdown

del f["d/h"] was a silent no-op. WritableDirectory._get_del_search split any
path on /, walked it and returned the selected object without ever calling
_del, so nothing was deleted and no error was raised. This affected histograms
and trees alike, with or without a cycle number.

What changed:

  • The last component of a path is now deleted from its parent directory, so
    d/h, d/h;1, /d/h, d/h/, d//h and d/ (a whole directory) all delete
    what they select. Paths that select nothing (d/nothere, d/h;9, d/t/x,
    d/t:x) still raise KeyInFileError and delete nothing.
  • WritableDirectory.__contains__ now agrees with item lookup for cycles and
    paths, so "h;2" in f and "d/h" in f are True, as they already were for
    read-only files. Recursive lookup of a bare name ("h" in f when the key lives
    in a subdirectory) is unchanged.
  • The cycle parsing used by both paths is factored out into _parse_name_cycle.

Testing

tests/test_1807_delete_by_path.py (new, 14 tests) covers deletion by path and
cycle, leading/trailing/doubled slashes, whole directories, trees, the
"selects nothing" errors, and in with cycles and paths.

  • python -m pytest tests/test_1807_delete_by_path.py -q: 14 passed with the fix.
    With src/uproot/writing/writable.py reverted, the same command gives 9 failed,
    5 passed.
  • python -m pytest tests -q -m "not network and not slow and not distributed and not xrootd" -n 8:
    4615 passed, 231 skipped, 2 failed. The two failures are
    test_1767_graphed_write_duplicate_paths.py::test_workers_read_the_path_as_given,
    which fail on this Windows machine with or without the change because creating a
    symlink needs a privilege the machine does not have (WinError 1314).
  • black --check and ruff check on both changed files: clean.
  • The new lines and branches in writable.py are covered by the new tests.

Fixes #1807

AI disclosure: this change was written with AI assistance (DeepSeek V4.1 Flash).

Deleting an object with a path, such as del f["d/h"], was a silent
no-op: _get_del_search walked the path and returned the selected object
without deleting anything. The last path component is now deleted from its
parent directory, so paths, cycles (d/h;1), leading and doubled slashes and
whole directories (d/) all work; a path that selects nothing still raises
KeyInFileError and deletes nothing.

WritableDirectory.__contains__ also agrees with item lookup for cycles and
paths now, so "h;2" in f and "d/h" in f match what f[...] can read.

Fixes scikit-hep#1807
@github-actions github-actions Bot added the type/fix PR title type: fix (set automatically) label Nov 22, 2026
@lyn1dev
lyn1dev marked this pull request as draft November 22, 2026 21:39
@lyn1dev
lyn1dev marked this pull request as ready for review November 23, 2026 18:59

@ariostas ariostas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI text below 🤖

Thanks for the fix! Deleting by path works as described. I left two inline comments: one on __contains__ loading objects during membership checks, and one on del f["/"] still doing nothing silently. Both include reproducers.

Comment thread src/uproot/writing/writable.py Outdated
Comment on lines +683 to +689
if isinstance(where, str) and (";" in where or "/" in where):
try:
self._get_del_search(where, True)
except uproot.KeyInFileError:
pass
else:
return True

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI text below 🤖

"d/t" in f now loads and builds the object it is checking for, because it goes through _get_del_search(where, True) and then _get. Only KeyInFileError is caught, so other errors from loading leak out of in.

On an uproot.update() of a file-like object, it raises instead of returning True, even though "t" in f["d"] works:

import numpy as np
import uproot

with uproot.recreate("m.root") as f:
    f.mktree("d/t", {"x": np.int64})
    f["d/t"].extend({"x": np.arange(3)})

class FileLike:  # any object that isn't a path
    def __init__(self, f): self.f = f
    def __getattr__(self, k): return getattr(self.f, k)

with open("m.root", "r+b") as fo, uproot.update(FileLike(fo)) as f:
    print("t" in f["d"])  # True
    print("d/t" in f)     # TypeError: uproot.update() on a file-like object does not support accessing existing TTrees

On main this returned False: wrong, but no crash. The same happens for RNTuples.

With an ordinary file path the answer is right, but checking membership has side effects. A writable tree or RNTuple is built and registered in f._file._trees or f._file._ntuples, and "h;2" in f reads and decompresses the whole histogram:

with uproot.update("m.root") as f:
    print(len(f._file._trees))  # 0
    "d/t" in f
    print(len(f._file._trees))  # 1

Could this check that the key exists instead of reading it? For example (untested sketch):

items = [item for item in where.split("/") if item != ""]
step = self
for item in items[:-1]:
    key = step._cascading.data.get_key(*_parse_name_cycle(item))
    if key is None or key.classname.string not in ("TDirectory", "TDirectoryFile"):
        return False
    step = step._subdir(key)
return bool(items) and step._cascading.data.get_key(*_parse_name_cycle(items[-1])) is not None

This would also make "/" in f return False (it is True now), which matches keys().

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated WritableDirectory.__contains__ in c2080b7ab590be6be5c0091daae55d358e80da84 to traverse subdirectories and inspect DirectoryData.get_key(*_parse_name_cycle(...)) without calling step[item] or loading objects.

  • Checking "d/t" no longer populates f._file._trees and works on uproot.update(file_object).
  • Trailing-slash, empty-path ("/", "//"), and non-directory intermediate ("h/x") checks now return False.
  • ruff check src/uproot/writing/writable.py, black --check, and pytest tests/test_1807_delete_by_path.py tests/test_1833_cov_writing_writable.py tests/test_1778_delete_older_cycle.py pass locally (64 passed, 8 skipped for optional ROOT/pandas, with full line+branch coverage on the modified lines).

Comment on lines +1032 to +1034
last_item = max(
(i for i, item in enumerate(items) if item != ""), default=None
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI text below 🤖

If the path has no non-empty parts, last_item is None, so nothing is deleted and step (the directory itself) is returned. That is the same silent no-op this PR fixes for other paths:

with uproot.update("m.root") as f:
    del f["/"]       # no error ("//" does the same)
    print(f.keys())  # ['d;1', 'd/t;1']: nothing deleted

main behaves the same way, so this isn't a regression, but it would be good to cover here. For example, raise KeyInFileError (or ValueError) when not isget and last_item is None.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated WritableDirectory._get_del_search in c2080b7ab590be6be5c0091daae55d358e80da84 to raise uproot.KeyInFileError when last_item is None and not isget (so del f["/"] and del f["//"] raise instead of returning self, while f["/"] still returns self). Added regression tests in tests/test_1807_delete_by_path.py.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type/fix PR title type: fix (set automatically)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Writable directories: del with a path is a silent no-op, and in ignores cycles

2 participants