Skip to content

glob returns a non-deterministic order for files with the same modification time #808

Closed

Description

What happens

src/tool/glob.ts collects matches and sorts them by modification time:

files.sort((a, b) => b.mtime - a.mtime)

There is no tiebreak. Array.prototype.sort is stable, so files with an identical mtime keep the order ripgrep's traversal produced, which is filesystem enumeration order.

The tool's own description (glob.txt:3) promises "Returns matching file paths sorted by modification time".

Why it is wrong

A checkout, a build, a git clone, or a script that writes files in one burst gives every file the same mtime. That is not an edge case — it is what a fresh clone looks like.

In that situation the ordering is decided by the filesystem, so two identical glob calls over an unchanged tree can return the same set of files in a different sequence. The model diffs two "same" results, sees files apparently appear and vanish, and either re-runs the search or reports a change that did not happen.

Verified on this machine: with four files pinned to one mtime, the pre-fix order was filesystem order (bravo, alpha, delta, charlie) rather than a defined one.

Repro

// four files, all with the same mtime
const first = await (await GlobTool.init()).execute({ pattern: "*.ts" }, ctx)
const second = await (await GlobTool.init()).execute({ pattern: "*.ts" }, ctx)
expect(first.output).toEqual(second.output)  // no ordering guarantee before the fix

test/tool/glob.test.ts did not exist — test/tool/ has grep, ls-tree, and read but nothing for glob.

Suggested fix

files.sort((a, b) => b.mtime - a.mtime || a.path.localeCompare(b.path))

This is a one-line comparator change; the new test file also pins the existing newest-first behaviour with genuinely distinct mtimes, so the primary ordering is unchanged.

Separate, deliberately not addressed here

The 100-file cap is applied during traversal, before the sort, so a truncated result is an arbitrary filesystem-order prefix rather than the 100 most recently modified matches. That is a truthful truncated: true, and deciding between "sort before slicing" (memory) and "say so in the note" is a design call rather than a bug fix, so it is left alone here.

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