Skip to content

symlinks can cause duplicate entries #138

Open

Description

@43081j

Given the following:

import mock from "mock-fs";
import { fdir } from "./dist/index.js";

mock({
  "/sym/linked": {
    "file-1": "file contents",
  },
  "/some/dir": {
    dirSymlink: mock.symlink({
      path: "/sym/linked",
    }),
    fileSymlink: mock.symlink({
      path: "/sym/linked/file-1",
    }),
  },
});
const api = new fdir().withSymlinks().crawl("/");
const files = await api.sync();
console.log(files);

files will contain the same entry 3 times (/sym/linked/file-1).

if you change this to withPromise (async), it will contain the same entry 2 times.

so there are two problems here:

  1. inconsistency between async and sync
  2. duplicating symlink resolutions

inconsistent results (async vs sync)

This is because async roughly visits the FS breadth-first (i.e. it visits all the top-level files, then 2nd level, and so on).

because of that, it visits /sym/linked before visiting /some/dir/dirSymlink. that means this code is hit and /sym/linked isn't queued up again (because the callback is never called thanks to this early return).

when we switch to sync mode, we visit the FS depth-first.

this means we visit /some/dir/dirSymlink before we visit /sym/linked. of course, that means we haven't yet visited it, so we queue it up to be visited.

meanwhile, when we do eventually visit /sym/linked normally (i.e. not because of the symlink), we don't check visited at all and push the result.

because of all of this, we get 2 copies of /sym/linked

duplicating symlink resolutions

the race condition explained above causes one of the duplicates. but that code isn't even really meant to be dealing with dupes, it exists to avoid infinite loops.

so this points at a deeper problem we should fix in the walker most likely, rather than trying to fix it in the symlink resolution code

basically, if we visit symlinks before the things they link to, we push them twice right now.

somewhere, we should probably be checking visited before traversing directories in the walker (visited is only directories afaict)

Activity

  1. thecodrr commented on Mar 25, 2025

    @thecodrr
    Owner

    Thank you for the detailed bug report. Will take a look at this soon. Feel free to open a PR if you have a working fix for this.

  2. 43081j commented on Mar 25, 2025

    @43081j
    ContributorAuthor

    i don't quite have a fix for it yet but will try take a look this week unless you beat me to it

    if anyone else wants to take a look too (or yourself), i think my suggestion is that when we encounter a directory, we always check if it is already in visited. this solves one half of the problem

    the other half of the problem is that you may have a symlink to a file, and those don't get tracked in visited. so this can happen:

    • visit /foo/symlink-1 (which resolves to /bar/file-1)
    • visit /bar/file-1

    we now have ['/bar/file-1', '/bar/file-1']. but in async, and if we visited them in reverse, we'd have one entry.

    this suggests we need to de-dupe in pushFile, but maybe that will affect performance?

  3. xyrolle commented on Oct 27, 2026

    @xyrolle

    I ran into this on a pnpm-style node_modules and traced the directory half on master.

    With real paths, visited is only consulted for symlinks (resolve-symlink.ts#L91-L93). A directory entry is always read (walker.ts#L115-L123). So when a link leads to a directory before the crawl reaches it, that directory is read twice. In pnpm's layout, the link in .pnpm/a@1.0.0/node_modules/b comes before .pnpm/b@1.0.0.

    The sync walker meets the link first. The promise walker usually reaches the folder first, because fs.realpath makes several requests per link. Which one wins is timing, though. On a pnpm tree of 1,303 directories, 5,036 files and 634 links, withSymlinks() returns 8,435 entries sync and 5,065 with promise.

    I have a fix for that half with tests, and will open it once #172 and #173 are in, since it touches the same visited line as #173. A directory that was already read with at least as much depth left isn't read again, so sync and promise both return 5,065 entries on that tree. With withMaxDepth(), a directory a link reached with less depth left is still read again, so some repeats remain there.

    On 336 crawls compared with master, using deterministic filters, it returns the same paths, none more often than master, and the same errors. For every failing promise crawl, only the error's code, errno and syscall are compared, not its path or message. Filters and exclude see a skipped directory's entries once instead of twice.

    The 29 repeats left are your second case, a file reached directly and through a file symlink (the .bin entries). Those are two entries on disk, so I left them alone. Should they be listed once, or once per route as now?

    Reproduction with fdir 6.5.0 and Node 24.16.0 on macOS. Run npm i fdir@6.5.0, then node repro.mjs:

    // A pnpm-style node_modules where package a depends on package b, crawled
    // with withSymlinks(): the sync API lists b's file twice, once through the
    // link in a's node_modules and once in b's own folder; the promise API
    // usually lists it once. Run with `node repro.mjs` after `npm i fdir@6.5.0`.
    import fs from "node:fs";
    import os from "node:os";
    import path from "node:path";
    import { fdir } from "fdir";
    
    const base = fs.mkdtempSync(
      path.join(fs.realpathSync(os.tmpdir()), "fdir-duplicates-")
    );
    const store = "node_modules/.pnpm";
    const entries = {
      [`${store}/a@1.0.0/node_modules/a/index.js`]: null,
      [`${store}/a@1.0.0/node_modules/b`]: "../../b@1.0.0/node_modules/b",
      [`${store}/b@1.0.0/node_modules/b/index.js`]: null,
    };
    for (const [name, target] of Object.entries(entries)) {
      const at = path.join(base, name);
      fs.mkdirSync(path.dirname(at), { recursive: true });
      if (target === null) fs.writeFileSync(at, "");
      else fs.symlinkSync(target, at);
    }
    
    const root = path.join(base, "node_modules");
    const print = (api, paths) => {
      console.log(`${api}:`);
      for (const p of paths.sort()) console.log(`  ${p.replace(base, "<tmp>")}`);
    };
    print("sync", new fdir().withSymlinks().crawl(root).sync());
    print("promise", await new fdir().withSymlinks().crawl(root).withPromise());
    
    fs.rmSync(base, { recursive: true, force: true });
    sync:
      <tmp>/node_modules/.pnpm/a@1.0.0/node_modules/a/index.js
      <tmp>/node_modules/.pnpm/b@1.0.0/node_modules/b/index.js
      <tmp>/node_modules/.pnpm/b@1.0.0/node_modules/b/index.js
    promise:
      <tmp>/node_modules/.pnpm/a@1.0.0/node_modules/a/index.js
      <tmp>/node_modules/.pnpm/b@1.0.0/node_modules/b/index.js
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions