Skip to content

Fix crash on circular import reached through a .. path - #18736

Merged
fdncred merged 4 commits into
nushell:mainfrom
hexbinoct:fix/circular-import-canonicalize
Nov 20, 2026
Merged

fdncred merged 4 commits into
nushell:mainfrom
hexbinoct:fix/circular-import-canonicalize

Conversation

@hexbinoct

@hexbinoct hexbinoct commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Description

On unix, importing a module that imports one of its parents back through a .. path never
terminates and nushell dies with a segfault instead of reporting a circular import (#18731):

mkdir /tmp/nucrash/c/i
"export module i" | save /tmp/nucrash/c/mod.nu
"use ../mod.nu"   | save /tmp/nucrash/c/i/mod.nu

nu -c "use /tmp/nucrash/c"
# Segmentation fault (core dumped)

The parser builds these paths with std::path::absolute, which drops . components but keeps
.. on unix, because a .. component is not the same thing as the parent directory once
symlinks are in play. FileStack, which is what detects circular imports, compared those paths
as they were, so /tmp/nucrash/c/mod.nu and /tmp/nucrash/c/i/../mod.nu looked like two
different files. Each trip around the cycle appended another /i/.. to the path, so the import
never repeated itself, the check never fired, and the parser recursed until the stack ran out.

That also explains why the symptom is not the same everywhere. Whether you get a crash depends
on which limit the growing path hits first: on macOS the path stops resolving before the stack
runs out, so it surfaces as a module_not_found naming a path with several hundred ../i
components in it, as @pickx saw on the issue. Windows was already fine, because
std::path::absolute resolves .. there, so the same repro reports nu::parser::circular_import
today. This makes the other platforms behave that way too.

Files on the stack are now identified by their canonical path, which resolves .. along with
symlinks pointing at a file that is already being parsed. The path a file was actually reached
by is kept as it was, since that is what error messages show and what the files it imports are
resolved against, so nothing else changes. Paths with no file behind them, such as the virtual
paths of the standard library, fall back to expanding . and .. textually.

Legitimate .. imports are unaffected: a module importing a sibling through ../other/mod.nu
still resolves and is not reported as circular (module_nested_imports_in_dirs covers this).

Tested on Linux, where the repro now prints a circular import error and exits 1 instead of
dying on SIGSEGV, and on Windows, where behavior is unchanged. The new regression test fails
on Linux without the fix and passes with it.

User-facing changes (Release notes)

Fixed a crash when importing a module that imports one of its parents back through a .. path,
for example a c/i/mod.nu containing use ../mod.nu. Nushell reported a circular import on
Windows but crashed on other platforms, and now reports the circular import everywhere.

Additional notes

fixes #18731

@pickx

pickx commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

so this stores the canonical path alongside the original path (as identity)
it uses the original path for error messages and the canonical path for comparison.
another option is to keep just the original path (as before) and also canonicalize on-the-fly inside push for comparison purposes
if this is correct, what's the perf impact of canonicalizing like this? because that seems simpler than storing both

@hexbinoct
hexbinoct force-pushed the fix/circular-import-canonicalize branch from 8c0b042 to e4a4e64 Compare July 27, 2026 00:47
@hexbinoct

Copy link
Copy Markdown
Contributor Author

Good question, I built both and measured instead of guessing.

Setup: a module chain N levels deep (root/mod.nu exports m1, m1/mod.nu exports m2, and so
on), timing nu -n -c "use root" with a nu -n -c true baseline subtracted so process startup is
out of it. Debug build on Windows, 11 runs, fastest run of each:

stack depth main this PR canonicalizing inside the comparison
8 within noise within noise within noise
32 28 ms 16 ms 73 ms
128 93 ms 152 ms 2575 ms

At the depths anyone actually hits, all three are the same to within run to run noise, so
canonicalizing is cheap. The two approaches only separate once the stack gets deep, and then they
separate hard, because storing the identity canonicalizes each file once as it is pushed, which is
N calls for depth N, while canonicalizing inside the comparison redoes every entry already on the
stack on every push, which is N(N+1)/2 calls. At depth 128 that is 8256 canonicalizations instead
of 128. The absolute numbers are a debug build on Windows, where canonicalize is on the expensive
side, but the linear versus quadratic shape is the same anywhere.

There is also a reason to keep the original path that is not about speed. pop, top and
current_working_directory hand back the path a file was reached by, and that path is what error
messages print and what relative imports inside that file resolve against. If the stack held only
canonical paths, a module under a symlinked directory would start resolving its ../x imports from
the symlink target rather than from where the user pointed at it, and diagnostics would show paths
the user never typed. Keeping both means the comparison gets physical identity while resolution and
messages keep the spelling the user used.

If you would still rather have the smaller struct I am happy to switch, it is a small change.

@pickx

pickx commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

thanks for checking! I think this call isn't mine to make. deferring to a more experienced maintainer.

@hexbinoct

Copy link
Copy Markdown
Contributor Author

Following up, since this has been waiting a couple of weeks for someone to pick it up after pickx deferred. To save the next reader the scrollback: the crash is real and the fix is small, and the only open question was pickx's, whether to canonicalize on the fly in push instead of storing the identity alongside the original path. I built both and posted the numbers above. They are indistinguishable at realistic module depths, and the on the fly version goes quadratic past that, so this PR keeps the original path for error messages and the canonical one only for the comparison. I am happy to switch to the simpler shape if that is preferred. Nothing is blocked on my side.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The implementation addresses the recursion failure while preserving path-resolution behavior and includes focused regression coverage.

Pull request overview

Canonicalizes file identities in FileStack to reliably detect circular imports through .. paths and symlinks while preserving original paths for resolution and errors.

Changes:

  • Separates display/resolution paths from canonical comparison identities.
  • Adds a regression test for parent-directory circular imports.
File summaries
File Description
crates/nu-protocol/src/engine/state_working_set.rs Canonicalizes file-stack identities.
tests/modules/mod.rs Tests circular imports through ...
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@fdncred

fdncred commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

is this still an issue? if so can you rebase on main?

The parser builds module and source paths with `std::path::absolute`, which
keeps `..` components on unix. `FileStack` compared those paths as they were,
so the same file reached as `c/mod.nu` and as `c/i/../mod.nu` counted as two
files and the circular import check never fired. Each trip around the cycle
appended another `/i/..`, so the parser recursed until the stack ran out.

Files on the stack are now identified by their canonical path, which resolves
`..` and symlinks, while the path a file was reached by is kept for error
messages and for resolving the files it imports. Paths with no file behind
them keep their textually expanded form.

Reported by @cornmonger, who pointed at the comparison in `FileStack`.
@hexbinoct
hexbinoct force-pushed the fix/circular-import-canonicalize branch from e4a4e64 to 8a1c777 Compare November 15, 2026 13:04
@hexbinoct

Copy link
Copy Markdown
Contributor Author

Yes it still happens. On main at b4993b5 (Linux), the repro from the issue ends with thread 'main' has overflowed its stack and fatal runtime error: stack overflow, aborting, exit code 134. I rebased onto that commit, and with the fix the same command reports nu::parser::circular_import and exits 1. The only conflict was in tests/modules/mod.rs, where a new test had landed in the same place, so I kept both.

@fdncred fdncred left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review overview

🟡 Changes recommended

The fix stops the .. cycle for use, overlay use and source. On macOS main reported a missing file with a c/i/../i/../... path, and the branch reports the circular import. Your numbers settle pickx's question for me: storing the identity once per file is fine. Two things are left: virtual std paths pick up the launch directory, and with_file now pays a realpath for every runtime working set in a script.

Findings: 1 High severity · 1 Medium severity · 1 Low severity

Open (3)

Notes from my clanker, checked on 8a1c777. Built the branch, ran cargo test --test tests -- modules:: parsing:: (273 passed), and ran each case on the branch binary and on 0.117.1. The timings compare the branch with a trial build of it where with_file skips canonicalizing, both debug. CI already ran clippy and the tests on this head, and I ran nothing on Linux or Windows.

Comment thread tests/modules/mod.rs Resolved
Standard library paths such as `std/log/mod.nu` are virtual, but they were
canonicalized against the process's current directory, so a real file at
that relative path took their identity and a module wrapping `std/log`
reported a circular import. The parser now tells `FileStack` which paths
are virtual, and those are compared by their path as given, never against
files on disk.

`with_file` canonicalized the root of every working set, which cost a
realpath for each caught error in a script. The root is now identified only
when a file on disk is pushed after it.

A file on disk is identified by the canonical path of the directory it was
reached in, joined with its name. A file resolves its imports against that
directory, so the same file reached through a symlink in another directory
is not a circular import. Windows device paths are kept as given.

Adds tests for `source` cycles through `..` and through a symlink, for the
std case and for the symlinked file.
@hexbinoct

Copy link
Copy Markdown
Contributor Author

One more change you didn't ask for. While going through every path that reaches FileStack, I found the canonical file path was too coarse. A file resolves its imports against the directory it was reached in, so one file reached through a symlink in another directory parses differently and isn't a cycle:

# d1/f.nu -> d2/f.nu (symlink)
# d2/f.nu:  source sib.nu
# d1/sib.nu: source ../d2/f.nu
# d2/sib.nu: 'd2 sib'
source d1/f.nu
# main:       d2 sib
# 8a1c77700:  Error: nu::parser::circular_import
# branch:     d2 sib

A file on disk is now identified by the canonical path of its directory joined with its name. That still stops every .. and symlink loop, because there are only so many directories and names to go around, and it is still one realpath per push. source_symlinked_file_from_two_dirs_is_not_circular covers it.

It isn't exact, and I'd like your view on it. Where .. is collapsed as text after going through a symlinked directory (path self ../x.nu on every platform, and every path on Windows), a file nested inside itself can still resolve somewhere else, so a chain that main finishes could stop with a circular import. Building one takes a symlinked directory and a file that imports itself through it. Comparing text alone, as main does, can't stop the symlink loops at all. The doc comment on FileIdentity::real says this.

What else changed: Windows device paths are kept as given, as on main. With nu --ide-check on a relative path, a plain cycle between two files is now reported where it closes, one file earlier than on main, because the root and the pushed file are now compared the same way.

What I ran, all on Linux, on main, on 8a1c777 and on the branch: 37 cases covering use, overlay use, source, run and run --full-reparse, the script and config roots, nu-check and --ide-check, through .., symlinks, a diamond, the std paths, and $env.PWD set apart from the launch directory. Main and the branch differ only where main crashed or reported a not found path dozens of segments long, plus the --ide-check case above. cargo test --test tests -- modules:: parsing:: passes, as do cargo test -p nu-protocol -p nu-parser, fmt and clippy.

On Windows, cargo test --test tests -- modules:: parsing:: passes on the branch (277), the two symlink tests included, and source NUL still works. On main on Windows only source_circular_through_symlink fails, with sourced_file_not_found as on Linux. The two .. tests pass there, because Windows collapses .. in the path as text.

Not tested: macOS and typos.

@fdncred fdncred left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review overview

🟢 Minor suggestions

All three threads are fixed on 18009bb and I've resolved them. One new low: the root's lazy identity has no test.

Findings: 0 High severity · 0 Medium severity · 1 Low severity

Open (1)

Notes from my clanker, checked on 18009bb. Built the branch on macOS and ran each case on it and on an installed 0.117.1 (c447af7): the std/log wrapper from two launch dirs and after a config cd, .. cycles through use, overlay use and source, symlink cycles through source, your d1/d2 example, plain and .. cycles under --ide-check, nu a.nu, nu-check and run --full-reparse. Ran cargo test --test tests -- circular cyclical with StackedFile::is changed so the root is never identified (10 passed). CI is green on this head; I didn't run anything on Windows.

Comment thread tests/parsing/mod.rs Resolved
@fdncred

fdncred commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

I'd keep the directory + name identity. On 18009bb on macOS, your d1/d2 example prints d2 sib on main and the branch, and both a b -> . loop and a two-name loop through l -> . stop with circular_import, where main gets 32 levels deep before sourced_file_not_found. The caveat reproduces as you describe: with t/L -> y/z and t/y/z/f.nu sourcing path self ../g.nu, source L/f.nu reaches t/y/g.nu on main and stops on the branch. That takes a symlinked directory and a file that comes back to itself through it. Anything that stops the symlink loops has to merge some paths like that, and reading the code, 8a1c777 merged this one too. Documented in FileIdentity::real is fine by me.

`nu a.nu` puts the script at the bottom of the file stack before it has an
identity. The new test runs a child nu on the `..` fixture and checks that
the cycle is reported where it closes, at `source ../a.nu`.
@hexbinoct

Copy link
Copy Markdown
Contributor Author

Thanks for running the cases on macOS, and for agreeing to keep the directory and name identity with the caveat in FileIdentity::real. a0cb6dc adds the script root test you suggested, and the details are in the thread. CI passes on it on Linux, macOS and Windows.

Not tested: your mutation and the main check on macOS and Windows. I ran those on Linux only.

@fdncred

fdncred commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

looks like we have a conflict now

@fdncred fdncred added notes:fixes Noted in "Bug fixes" section notes:ready Indicates Ready for Release notes labels Nov 19, 2026
Port the six new tests to the new `Playground` from nushell#18915, which
removed `Playground::setup`.
@hexbinoct

Copy link
Copy Markdown
Contributor Author

Fixed by merging main. #18915 removed Playground::setup, so the only change is that our six tests now use the new Playground; the fix itself is untouched.

@fdncred
fdncred merged commit 624b8ed into nushell:main Nov 20, 2026
14 checks passed
@fdncred

fdncred commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Thanks

@github-actions github-actions Bot added this to the v0.118.0 milestone Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

notes:fixes Noted in "Bug fixes" section notes:ready Indicates Ready for Release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Segfault on circular import

4 participants