Skip to content

detect circular module imports to prevent stack overflow - #347

Merged
itchyny merged 6 commits into
itchyny:mainfrom
daichunghy:fix/346-circular-import
Dec 1, 2026
Merged

itchyny merged 6 commits into
itchyny:mainfrom
daichunghy:fix/346-circular-import

Conversation

@daichunghy

Copy link
Copy Markdown
Contributor

Fix #346

When a module imports itself (directly, through another module, or via include), gojq keeps recursing in compileModule until the Go runtime aborts with a stack overflow (about 25 s and 1.5 GB in the report).

The compiler now keeps track of the modules being compiled. If an import refers to a module already on the stack, it returns a circular import of "name" compile error, matching what jq reports. Each module is marked only for the duration of its compilation, so importing the same module from two separate branches (a diamond) still works.

TestCompile_CircularImport covers all three cases from the issue (self-import, two-module cycle, self-include). These crash the test binary with a stack overflow on unmodified main and pass with the fix. TestCompile_DiamondImport checks that diamond imports still work.

go test -race ./... passes, same as the unmodified baseline.

Comment thread compiler.go Outdated
scopes []*scopeinfo
scopecnt int
regexpCache sync.Map
importing map[string]bool

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Use map[string]struct{} if we don't use false value. Differs allocation size.

@daichunghy

Copy link
Copy Markdown
Contributor Author

Updated. The importing set now uses map[string]struct{} with a comma-ok membership check. go vet is clean, and go test ./... passes, including the circular import and diamond import tests.

Comment thread compiler.go Outdated
return nil
}
path = filepath.Clean(path)
if _, ok := c.importing[path]; ok {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Using path for the key is wrong. They don't honor the search path.

# lib/foo.jq
import "foo" as f {search: "./vendor"}; def a: f::b + 1;
# lib/vendor/foo.jq
def b: 1;

 $ ./gojq -n -L lib 'import "foo" as f; f::a'
main: 2
PR:   gojq: compile error: circular import of "foo"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, you were right. The cycle key was the raw import string, so importing the same module name through a different search path caused a false collision. The key now combines the import path with its cleaned search metadata, so import "foo" as f {search: "./vendor"} inside lib/foo.jq resolves as a separate module, while a self-import through the same search path still reports a circular import.

I added TestCompile_ImportWithSearchPath, which fails on the previous head with a false circular import of "foo" and now passes (the program prints 2, matching jq), along with TestCompile_CircularImportWithSearchPath to cover the genuinely circular case.

The full test suite, race detector, go vet, and staticcheck are all green.

Comment thread compiler.go Outdated
}
path = filepath.Clean(path)
key := path
if search, ok := i.Meta.ToValue()["search"].(string); ok && search != "" {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This is not good. The search path is the feature of file system module loader, so its knowledge should not be leaked to the compiler. But, being need to check circular dependency here, we'll have to use i.Meta.String().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both addressed. The cycle key is now the import path plus i.Meta.String(), so the compiler no longer extracts or interprets search-path metadata itself. Meta.String() distinguishes the same module reached through different search paths ({} versus { search: "./vendor" }).

One catch: Meta can be nil for plain imports, and Meta.String() panics on nil, so nil is treated as "{}", which is what an empty Meta renders as.

I've removed filepath.Clean from both the path and the key, along with the unused filepath import. Cycles are still detected because the key space is finite and a cycle must repeat a key exactly. The map was already map[string]struct{} on the original head, so no change was needed there.

Both search-path tests pass unchanged, the exact example still prints 2, and the full suite, race detector, go vet, gofmt and staticcheck are all green.

Comment thread compiler.go Outdated
c.append(&code{op: opstore, v: c.pushVariable(alias + "::" + alias[1:])})
return nil
}
path = filepath.Clean(path)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Don't clean path here. Treating a name as a file path is the loader's job. Cycles should still stop without clean.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both addressed. The cycle key is now the import path plus i.Meta.String(), so the compiler no longer extracts or interprets search-path metadata itself. Meta.String() distinguishes the same module reached through different search paths ({} versus { search: "./vendor" }).

One catch: Meta can be nil for plain imports, and Meta.String() panics on nil, so nil is treated as "{}", which is what an empty Meta renders as.

I've removed filepath.Clean from both the path and the key, along with the unused filepath import. Cycles are still detected because the key space is finite and a cycle must repeat a key exactly. The map was already map[string]struct{} on the original head, so no change was needed there.

Both search-path tests pass unchanged, the exact example still prints 2, and the full suite, race detector, go vet, gofmt and staticcheck are all green.

Comment thread compiler.go Outdated
if i.Meta != nil {
meta = i.Meta.String()
}
key := path + "\x00" + meta

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Use map[[2]string]struct{} for importing. The code of concatenation by the nul character looks ugly.

Comment thread compiler.go Outdated
// Meta.String() distinguishes the same module reached through
// different search paths, while the same path with the same meta
// still collides. A nil meta renders as "{}", matching an empty
// object literal; calling String() on nil would panic, so guard it.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Please drop this comment. This comment just explains what the code does, not why. Code tells me enough.

@itchyny itchyny changed the title fix: report circular module imports instead of overflowing the stack (#346) detect circular module imports to prevent stack overflow Dec 1, 2026
@itchyny
itchyny merged commit 40cd181 into itchyny:main Dec 1, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Circular module import/include crashes with a Go stack overflow

2 participants