Repository navigation
fileserver: speed up directory browsing for large directories - #7903
Conversation
There was a problem hiding this comment.
Pull request overview
This PR optimizes the file server’s directory browsing path for very large directories by reducing avoidable allocations during listing construction and removing repeated strings.ToLower() work from sort comparisons.
Changes:
- Preallocates the directory listing
Itemsslice and reduces redundantstatcalls for symlinks during listing construction. - Speeds up sorting by caching each item’s lowercase name once instead of recomputing it in every comparator call.
- Adds parity tests and benchmarks comparing “old” vs “new” implementations (with old implementations temporarily retained for benchmarking).
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| modules/caddyhttp/fileserver/browsetplcontext.go | Optimizes directory listing construction and sorting; adds temporary “Old” implementations and cached lowercase name field. |
| modules/caddyhttp/fileserver/browsetplcontext_test.go | Adds parity tests to ensure optimized behavior matches previous output. |
| modules/caddyhttp/fileserver/browsetplcontext_bench_test.go | Adds benchmarks to measure old vs new performance on large directories and sorting. |
| modules/caddyhttp/fileserver/browse.go | Marks isSymlinkTargetDir as unused (temporarily) for benchmark comparison support. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
Comments suppressed due to low confidence (3)
modules/caddyhttp/fileserver/browsetplcontext_test.go:148
- Using os.DirFS(dir) here means the code will attempt fs.Stat/os.Readlink with absolute paths (built via SanitizedPathJoin(root, ...)), which DirFS will reject; that makes the parity test less representative of real browse behavior for symlinks. Use filesystems.OsFS and read entries from the absolute dir path instead.
fileSystem := os.DirFS(dir)
entries, err := fileSystem.(fs.ReadDirFS).ReadDir(".")
if err != nil {
t.Fatal(err)
}
modules/caddyhttp/fileserver/browsetplcontext_bench_test.go:78
- Using os.DirFS(dir) here causes fs.Stat inside directoryListing (for symlink target inspection) to be called with absolute paths, which DirFS rejects. That means the benchmark is not measuring the real stat/syscall behavior that browse uses in production. Use filesystems.OsFS{} and open the absolute dir path so ReadDir returns filesystem-order entries without the DirFS absolute-path mismatch.
fileSystem := os.DirFS(dir)
f, err := fileSystem.Open(".")
if err != nil {
tb.Fatal(err)
}
modules/caddyhttp/fileserver/browsetplcontext.go:349
- applySortAndLimit precomputes nameLower for every item even when sorting by time (or if sorting is skipped). That adds an unconditional O(n) allocation/cpu cost on every browse response, including cases where byTime is selected and nameLower is never read. Consider computing the cache only for sort modes that actually consult nameLower (name, namedirfirst, size).
// precompute each item's lowercase name once, up front (O(n)), instead
// of letting byName/byNameDirFirst/bySize recompute it on every one of
// the O(n log n) comparisons sort.Sort makes
for i := range l.Items {
l.Items[i].nameLower = strings.ToLower(l.Items[i].Name)
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (1)
modules/caddyhttp/fileserver/browsetplcontext.go:350
- The nameLower cache is computed unconditionally, even when sorting by time (or when no name-based sort is selected). For large directories this adds an extra O(n) scan and potentially many allocations that provide no benefit unless the comparator needs nameLower (name/namedirfirst/size).
// precompute each item's lowercase name once, up front (O(n)), instead
// of letting byName/byNameDirFirst/bySize recompute it on every one of
// the O(n log n) comparisons sort.Sort makes
for i := range l.Items {
l.Items[i].nameLower = strings.ToLower(l.Items[i].Name)
}
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (5)
modules/caddyhttp/fileserver/browsetplcontext.go:350
- applySortAndLimit now lowercases every item name unconditionally, even when sorting by time (byTime doesn’t use name comparisons). For large directories, a user-requested
sort=timebecomes an O(n) extra allocation/CPU cost that wasn’t present before; consider filling nameLower only for the name-based comparators.
// precompute each item's lowercase name once, up front (O(n)), instead
// of letting byName/byNameDirFirst/bySize recompute it on every one of
// the O(n log n) comparisons sort.Sort makes
for i := range l.Items {
l.Items[i].nameLower = strings.ToLower(l.Items[i].Name)
}
modules/caddyhttp/fileserver/browsetplcontext_test.go:28
- The parity test needs an fs.FS that accepts the absolute paths produced by caddyhttp.SanitizedPathJoin (which production uses). With os.DirFS, fs.Stat on those absolute paths fails with fs.ErrInvalid, so symlink target stats/directory detection aren’t actually exercised and the test can give false confidence.
"go.uber.org/zap"
"github.com/caddyserver/caddy/v2"
)
modules/caddyhttp/fileserver/browsetplcontext_test.go:148
- Using os.DirFS here means symlink target stats will fail (directoryListing uses SanitizedPathJoin(root, ...) which yields absolute paths). Switch to the same absolute-path fs.FS style as production (internal/filesystems.OsFS) and read entries by opening the actual directory path.
fileSystem := os.DirFS(dir)
entries, err := fileSystem.(fs.ReadDirFS).ReadDir(".")
if err != nil {
t.Fatal(err)
}
modules/caddyhttp/fileserver/browsetplcontext_bench_test.go:31
- The benchmarks should use the same absolute-path fs.FS semantics as production (SanitizedPathJoin returns OS paths under root). Add internal/filesystems so readBenchDirEntries can return an fs.FS that accepts those paths; otherwise symlink-target fs.Stat calls can fail early with fs.ErrInvalid on os.DirFS and skew results.
"go.uber.org/zap"
"github.com/caddyserver/caddy/v2"
)
modules/caddyhttp/fileserver/browsetplcontext_bench_test.go:85
- os.DirFS constrains Stat/Open to relative paths, but directoryListing builds absolute OS paths via SanitizedPathJoin(root, ...). That mismatch can make symlink-target stats fail with fs.ErrInvalid (and avoid real syscalls), skewing the directoryListing benchmarks. Consider using internal/filesystems.OsFS and opening dir by its full path.
fileSystem := os.DirFS(dir)
f, err := fileSystem.Open(".")
if err != nil {
tb.Fatal(err)
}
defer f.Close()
entries, err := f.(fs.ReadDirFile).ReadDir(-1)
if err != nil {
tb.Fatal(err)
}
return fileSystem, entries
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (3)
modules/caddyhttp/fileserver/browsetplcontext.go:351
- These lines also have leading spaces before tabs (not gofmt-formatted). Please gofmt the file so indentation is consistent.
if l.Sort == sortByName || l.Sort == sortByNameDirFirst || l.Sort == sortBySize {
for i := range l.Items {
l.Items[i].nameLower = strings.ToLower(l.Items[i].Name)
}
}
modules/caddyhttp/fileserver/browsetplcontext.go:156
- The *Old implementations (directoryListingOld/applySortAndLimitOld and the old comparator types) are currently in non-test code, which means they’ll ship in production builds and require //nolint directives. Consider moving the old implementations into *_test.go (still in package fileserver) so benchmarks/parity tests can use them without adding dead code to the binary.
// directoryListingOld is the previous implementation of directoryListing, kept
// temporarily so its performance can be compared against directoryListing via
// benchmarks (see browsetplcontext_bench_test.go). It is unused in production
// code and should be deleted, along with its benchmark and parity test, once
// the new implementation has been merged and validated.
modules/caddyhttp/fileserver/browse.go:340
- Since isSymlinkTargetDir is now only needed by directoryListingOld for benchmarks/parity tests, consider moving/removing it along with the other Old code so this production file doesn’t need a //nolint:unused directive.
// isSymlinkTargetDir returns true if f's symbolic link target
// is a directory.
//
//nolint:unused // only called from directoryListingOld, kept temporarily for benchmark comparison; see browsetplcontext_bench_test.go
func (fsrv *FileServer) isSymlinkTargetDir(fileSystem fs.FS, f fs.FileInfo, root, urlPath string) bool {
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 6 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (2)
modules/caddyhttp/fileserver/browsetplcontext_test.go:148
- Using os.DirFS(dir) here makes file paths produced by caddyhttp.SanitizedPathJoin(root, urlPath+name) incompatible with fs.Stat and os.Readlink calls inside directoryListing/directoryListingOld (they produce absolute OS paths, but os.DirFS expects paths relative to dir). As a result, symlink target stats (dir vs file, target size) and RevealSymlinks behavior are not actually exercised by this parity test.
fileSystem := filesystems.OsFS{}
entries, err := fileSystem.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
modules/caddyhttp/fileserver/browsetplcontext_bench_test.go:86
- readBenchDirEntries uses os.DirFS(dir), but the production fileserver uses a filesystem that operates on OS paths (see caddyhttp.SanitizedPathJoin returning filepath.Join(root, relPath)). With os.DirFS, the absolute paths generated for symlink stats (and os.Readlink) won't work, so the benchmarks don't measure the real stat/readlink behavior or the claimed reduction of duplicate stats for symlinks.
fileSystem := filesystems.OsFS{}
f, err := fileSystem.Open(dir)
if err != nil {
tb.Fatal(err)
}
defer f.Close()
entries, err := f.(fs.ReadDirFile).ReadDir(-1)
if err != nil {
tb.Fatal(err)
}
return fileSystem, entries
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 6 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (2)
modules/caddyhttp/fileserver/browsetplcontext.go:351
- applySortAndLimit precomputes nameLower for every item when sorting by size, but bySize only needs nameLower for directory-vs-directory comparisons. On large listings with few directories, this does avoidable O(n) allocations/work. Consider computing nameLower for all items only for name-based sorts, and only for directories when sorting by size.
if l.Sort == sortByName || l.Sort == sortByNameDirFirst || l.Sort == sortBySize {
for i := range l.Items {
l.Items[i].nameLower = strings.ToLower(l.Items[i].Name)
}
}
modules/caddyhttp/fileserver/browsetplcontext.go:156
- directoryListingOld/applySortAndLimitOld and the *Old comparator types are kept in non-test files, so they ship in production builds and require nolint suppressions. If these are only for parity tests/benchmarks, consider moving them (and isSymlinkTargetDir, if needed) into a _test.go file so they don’t increase shipped code size/surface area.
// directoryListingOld is the previous implementation of directoryListing, kept
// temporarily so its performance can be compared against directoryListing via
// benchmarks (see browsetplcontext_bench_test.go). It is unused in production
// code and should be deleted, along with its benchmark and parity test, once
// the new implementation has been merged and validated.
|
Added the changes and updated the benchmark results in the description |
steadytao
left a comment
There was a problem hiding this comment.
The conditional name normalisation and OsFS corrections address my earlier concerns. The remaining blocker is the old implementation being retained in production behind nolint; please remove that dead code and the unrelated test formatting churn.
Do you want me to also remove all temporary benchmarks? |
|
The benchmarks for the new implementation can remain as useful regression measurements; there is no need to remove benchmarking entirely. |
|
Just removing the old implementations and the old-vs-new parity/benchmark cases that depend on them would be fine. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 5 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
modules/caddyhttp/fileserver/browsetplcontext.go:236
- The PR description says parity tests (TestDirectoryListingParity/TestApplySortAndLimitParity) and temporary Old implementations (directoryListingOld/applySortAndLimitOld/byNameOld/...) were added/kept, but those identifiers/tests don't exist anywhere in the repo. Either add the promised parity tests/Old implementations, or update the PR description so reviewers aren’t relying on non-existent comparisons.
// Only compute lowercase names when the selected sort comparator needs it;
// avoid O(n) work when sorting by time or when no sorting is requested.
if l.Sort == sortByName || l.Sort == sortByNameDirFirst || l.Sort == sortBySize {
for i := range l.Items {
l.Items[i].nameLower = strings.ToLower(l.Items[i].Name)
|
@steadytao done |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 5 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (3)
modules/caddyhttp/fileserver/browsetplcontext_bench_test.go:114
- The benchmarks currently only exercise the new implementation, but the PR description claims Old/New versions plus parity tests exist (e.g. directoryListingOld/applySortAndLimitOld and Test*Parity). Either update the PR description or add the referenced old implementations/tests so reviewers can validate equivalence as described.
func BenchmarkDirectoryListing(b *testing.B) {
for _, n := range []int{100, 1_000, 10_000, 50_000} {
b.Run(fmt.Sprintf("entries=%d", n), func(b *testing.B) {
benchmarkDirectoryListing(b, n, func(fsrv *FileServer, ctx context.Context, fileSystem fs.FS, entries []fs.DirEntry, root string) *browseTemplateContext {
return fsrv.directoryListing(ctx, fileSystem, time.Time{}, entries, true, root, "/", caddy.NewReplacer())
modules/caddyhttp/fileserver/browsetplcontext_bench_test.go:59
- Skipping the entire benchmark when symlink creation fails prevents running these benchmarks on platforms/configs where symlinks are disallowed (e.g. Windows without privileges). It would be better to continue and just omit the symlink entries, since the main performance characteristics (large file counts + sorting) can still be measured.
if err := os.Symlink(target, filepath.Join(dir, "symlink-to-file")); err != nil {
tb.Skipf("symlink not supported on this platform: %v", err)
}
modules/caddyhttp/fileserver/browsetplcontext_bench_test.go:85
- This unchecked type assertion will panic if the underlying fs.File does not implement fs.ReadDirFile. Even though OsFS currently returns an *os.File, guarding the assertion makes the benchmark more robust and fails with a clear message instead of a panic.
entries, err := f.(fs.ReadDirFile).ReadDir(-1)
if err != nil {
tb.Fatal(err)
}
Fixes #7902
The Benchmarks in this PR and the unused functions can be deleted after the PR is merged (hopefully :)). They are kept to measure the actual difference on big directories using golang benchmarks
Assistance Disclosure
Claude was used to generate the benchmarks, tests, verify the implementation, add comments and generate a good PR description
Description
Directory browsing (
browse) was slow for directories with tens of thousandsof entries due to allocation-heavy listing construction and an O(n log n)
strings.ToLowerrecomputation in the sort comparators (called on everysingle comparison instead of once per item).
Changes
directoryListing(listing construction): preallocates theItemsslice instead of growing it via unprepended
append, and merges the twoseparate
Statcalls the old code made per symlink (one to check if thetarget is a dir, one to get its size) into one.
applySortAndLimit(sorting): precomputes each item's lowercase nameonce, up front, instead of letting
byName/byNameDirFirst/bySizerecompute it on every one of the O(n log n) comparisons
sort.Sortmakes.directoryListingOld,applySortAndLimitOld,byNameOld,byNameDirFirstOld,bySizeOld(
//nolint:unused), used only by the benchmarks/parity tests below, soreviewers can compare old vs. new directly. These should be deleted once
this PR is reviewed/merged.
TestDirectoryListingParityandTestApplySortAndLimitParity,which assert old and new produce identical output/ordering.
Benchmarks
Machine: AMD Ryzen 7 9700X,
go test -bench Benchmark -benchtime=10x, realon-disk temp directories (not in-memory fakes), directory entries read via
the same unsorted, filesystem-order
ReadDircall path production uses.Speedup summary (ns/op, higher entry counts are the representative case):
DirectoryListing(build only)SortByNameSortByNameDirFirst(default)SortBySizeDirectoryListingAndSort(whole request path)Wall-clock time on
DirectoryListing/DirectoryListingAndSortis boundedby the
lstatsyscall per entry (needed for size/mtime and inherent to thefeature), so the gain there is more modest than the sort comparators, whose
ToLower-per-comparison cost is pure CPU/allocation waste that's now goneentirely. Memory allocated drops by ~43–45% at 50,000 entries either way.