Repository navigation
Speed up TAR file listing - #2304
martindurant merged 1 commit into
Conversation
| type(self) is not TarFileSystem | ||
| or kwargs | ||
| or type(withdirs) is not bool | ||
| or type(detail) is not bool | ||
| or (maxdepth is not None and (type(maxdepth) is not int or maxdepth < 1)) |
There was a problem hiding this comment.
We do not need to exhaustively check types.
| type(self) is not TarFileSystem | |
| or kwargs | |
| or type(withdirs) is not bool | |
| or type(detail) is not bool | |
| or (maxdepth is not None and (type(maxdepth) is not int or maxdepth < 1)) | |
| kwargs | |
| or (maxdepth is not None and maxdepth < 1) |
Maybe even we're OK with kwargs too - what meaningful impact can it have?
There was a problem hiding this comment.
Indeed, even in such a case, it might be fine to call _get_dirs() so that it happens exactly once before those arguments are processed.
There was a problem hiding this comment.
I checked the kwargs case. find("missing", on_error="raise") raises FileNotFoundError, and passing an error callback calls it once. Ignoring those options would change that behaviour. topdown doesn't change the sorted result, and TAR's ls ignores refresh.
The exact type checks are more defensive than this needs, though. I added them to keep unusual inputs and subclass overrides on the old path, rather than because the faster lookup needs them. I'm fine with simplifying that part; on_error is the option I wouldn't silently ignore.
Calling _get_dirs() up front sounds fine for the normal path too. Once the cache exists, that call just returns.
| path = self._strip_protocol(path) | ||
| self._get_dirs() | ||
| if path in self.dir_cache and self.dir_cache[path]["type"] != "directory": | ||
| return super().find(path, maxdepth, withdirs, detail) |
There was a problem hiding this comment.
This finds a single file, fine.
But why do we need the rest of this method? If we've made a cache of all the files/directories, is that not enough for fund/ls/walk/glob to all work as-is?
There was a problem hiding this comment.
That branch is just the single-file fallback. The rest is for finding files under a directory.
The cache is already enough for correct results, yes. The catch is that ls() still scans every entry in dir_cache each time it's called. The old find() walks the directories and calls ls() for each one, even when the cache was built earlier.
I just checked django/core with the cache built before either call. Both versions returned the same 111 files. The old method called ls() 15 times, each scanning the 10,296-entry cache. This method uses one pass over that cache instead. Neither version rebuilt the cache during the check.
So calling _get_dirs() once doesn't remove those repeated scans. ls() and walk() are unchanged by this PR; glob() benefits because it calls find().
There was a problem hiding this comment.
For the unlikely 10296-entry tar, what speed difference do you see?
There was a problem hiding this comment.
That cache comes from the Django 6.1.2 source tarball, not a generated archive. I tested find("django-6.1.2/django/core"); both versions return the same 111 files.
On one CPU pair, using the median of five runs per version:
| Operation | Before | After | Speed |
|---|---|---|---|
| find with the cache already built | 516.020 ms | 2.465 ms | 209.3x faster |
| Open, index, find and close | 1,867.556 ms | 1,500.854 ms | 1.24x faster |
Across all four CPU pairs, the cached lookup was 153-222x faster. Including opening and indexing, it was only 1.03-1.27x faster. Those small differences are noisier on this laptop.
So the large gain is in queries after the archive has been indexed, not the whole first read. The 10,296 cache entries still get scanned once rather than once for each visited directory. Opening and building the index are unchanged by this PR.
The full table, including the controls and slower results, is in the PR. The runner and raw samples are linked there too.
|
Hi @martindurant, |
Closes #2303.
TAR find currently lists each directory separately, and every listing scans the whole directory cache again.
This reads the existing cache directly, picks the paths under the requested folder, and sorts the result as before. It doesn't add another persistent index.
The old walk is still used for subclasses, custom walk options, unusual depth values, and archives where a file masks a directory. That keeps those cases on the same path instead of trying to guess what they should return.
I compared 2,905 calls against the old code, including cold and warm caches, metadata and ordering, missing paths, files, empty folders, links, duplicate names, literal parent components, depth limits and recursive globs. They matched, including 86 errors.
The archive checks passed: 340 passed, 28 skipped. The broader filesystem checks passed too: 579 passed, 129 skipped and one expected failure. Those broader checks give the same Windows test-server warning on both versions. I haven't run every optional remote backend.
With N cached entries and D visited folders, the repeated listing scans go from O(N × D) to one O(N) scan, plus checking ancestor paths and sorting the results. If M entries match the path and depth, H is their maximum path depth, and K entries are returned, that work is O(N + M × H + K log K), ignoring string lengths and using normal dictionary lookup costs. The result still takes O(K) space; the existing archive cache isn't duplicated. Fallback cases still use the old walk and can pay for checking the fast path first.
The benchmarks use Django's actual source archive. Warm listings and opening/indexing/listing are measured separately, so a large warm-listing gain isn't presented as the gain for the whole operation. All the results are below, including the small controls.
One real use of this path is finding NetCDF outputs inside a TAR archive. This change only speeds up listing an archive that's being read; it doesn't implement the saved index requested in that issue.
Measurements: Python 3.15.0, Windows, Intel Core i5-13420H. Each row is the median of five paired timing samples on that same CPU pair. Short calls are batched. Only one process runs, allowed on two physical cores at a time, with the pairs rotated. The masks are kept separate because this CPU has different core types. Run order alternates on successive visits to each pair.
Peak figures are medians of five separate tracemalloc runs, not total process RAM. A separate memory run is shared by the four timing rows for a workload. Small timing differences on this laptop should not be treated as guaranteed gains or losses.
Base commit: 5a22bb2. Fixture loading is outside the warm measurements. The Django archive is version 6.1.2, SHA-256 a1e92451ccb8b514e91bbb3b6d186d20b4030558f116b5d9de6535455ff210b7.
The benchmark scripts, input details and raw samples are available here. All 40 result rows are included below.
I rebased onto 16fad61 and reran the tests and comparisons. That upstream update only changes HTTP writes; the TAR, archive and generic find code used for these timings is unchanged.
All TAR listing benchmarks