Resolve literal glob prefixes in a single traversal

This commit is contained in:
2026-12-05 22:11:14 +00:00
parent b38bd101f2
commit 8d6622722b
5 changed files with 162 additions and 47 deletions

View File

@@ -77,10 +77,14 @@ bootstrap also uses the captured legacy anchor, independently of importRoot.
Literal selector resolution in `import_selection.go` distinguishes host absolute
paths, native namespace-root selectors, and relative bases before candidate
normalization. Glob roots are separated from pattern segments without whole-pattern
cleaning. The longest literal prefix is inspected component by component before
discovery, permitting resolution ancestors of explicit roots without enumerating
them. Parent segments after wildcards advance from inspected matched directories,
retaining lexical candidates separately from physical access paths.
cleaning. The longest literal prefix is consumed by one invocation of the shared
link evaluator from its resolved base. A component visitor performs directory,
access and containment checks as the cursor advances, preserving lexical source
spelling separately from resolved traversal coordinates. This avoids restarting
ancestor resolution at every literal component and permits resolution ancestors
of explicit roots without enumerating them. Parent segments after wildcards
advance from inspected matched directories, retaining lexical candidates separately
from physical access paths.
Glob selection keeps traversal coordination in `selectGlobImportCandidates`:
it advances literal and patterned segments, reads directories, unions and sorts

View File

@@ -3,7 +3,9 @@
Reviewed commit: `9d86e3377a5f462bc7b9eb572aff881abd1b70b3`.
Scope: all 15 stages of the [implementation plan](implementation.md), compared
with the [agreed roadmap](absolute-imports.md), ADR 0026, and the current contracts.
This review changes no production code or tests.
Remediation status: complete. All four findings have been addressed. The review
descriptions and audit evidence below are historical; completion notes record
the subsequent fixes.
## 1. Resolve native link targets before parent steps in a literal glob prefix
@@ -177,7 +179,20 @@ access as well, since it shares the normalization defect.
## 4. Avoid repeatedly resolving the ancestors of every literal glob prefix
Priority: P3. Status: open for consideration.
Priority: P3. Status: complete.
Completed: literal prefixes now advance through one shared link evaluator from
an already resolved base. A component visitor retains directory/access errors,
containment checks and native source spelling. Completed-link metadata supports
continued traversal without re-inspection, and native target components retain
filesystem order. The semantic regression also covers a literal native glob
through a compound link target.
A disposable Go test overlay (outside the checkout, with no permanent count
assertions) compared link-free native prefixes at depths 8/16/32. Component
operations changed from 63/187/627 to 29/53/101. These are inspection counts,
not timing claims. Focused filesystem tests, `./scripts/check.sh`, and
`go test -race ./...` pass; changed local links and whitespace checks pass.
Relevant code: the loop in `globStartingCandidates`, lines 344–365 of
[glob.go](../../internal/engine/glob.go); `explicitGlobCandidate` in that file;
@@ -247,7 +262,7 @@ public performance promise.
Integration follow-up reviewed at `22a022a9e85a37ccf7a77f6823412c34359f9d3e`;
production code remains at the implementation revision identified above.
Findings 1 and 2 remain open. This follow-up adds finding 3.
At that review, findings 1 and 2 remained open; the follow-up added finding 3.
| Stage | Interaction reviewed | Result |
| --- | --- | --- |
@@ -282,7 +297,7 @@ were changed, and no publication or downstream dependency updates were made.
## Algorithmic audit coverage
Reviewed at `cda0fa5`, with production code still at `9d86e33`. All stages were
considered in order. This follow-up adds finding 4; findings 1–3 remain open.
considered in order. That follow-up added finding 4; findings 1–3 were still open.
| Stage | Algorithmic assessment |
| --- | --- |

View File

@@ -140,9 +140,17 @@ type importLinkOperations struct {
lstat func(string) (fs.FileInfo, error)
readlink func(string) (string, error)
normalizeTarget func(string, string) (string, error)
// visit observes completed input components, not components of link targets.
visit func(string, fs.FileInfo) error
}
func resolveImportLinkPath(name string, operations importLinkOperations) (string, error) {
return resolveImportLinkPathFrom("", name, operations)
}
// base is an already resolved directory. Link expansions still start in their
// own root coordinates and use the same active/completed frame state.
func resolveImportLinkPathFrom(base, name string, operations importLinkOperations) (string, error) {
split := func(name string) (string, []string) {
root := ""
if operations.pathRoot != nil {
@@ -151,9 +159,23 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
return root, strings.Split(strings.TrimPrefix(name, root), "/")
}
resolved, pending := split(name)
if resolved == "" {
resolved = base
}
visit := func(info fs.FileInfo) error {
if operations.visit == nil {
return nil
}
return operations.visit(resolved, info)
}
frames := []importLinkFrame{{pending: pending}}
active := make(map[string]struct{})
completed := make(map[string]string)
var resolvedInfo fs.FileInfo
type resolvedLink struct {
path string
info fs.FileInfo
}
completed := make(map[string]resolvedLink)
for len(frames) > 0 {
frame := &frames[len(frames)-1]
if len(frame.pending) == 0 {
@@ -161,12 +183,20 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
if resolved == "" {
resolved = "."
}
completed[frame.link] = resolved
completed[frame.link] = resolvedLink{resolved, resolvedInfo}
delete(active, frame.link)
}
frames = frames[:len(frames)-1]
if frame.link != "" && len(frames) == 1 && operations.visit != nil {
if err := visit(resolvedInfo); err != nil {
return "", err
}
}
continue
}
if resolvedInfo != nil && !resolvedInfo.IsDir() {
return "", fs.ErrInvalid
}
segment := frame.pending[0]
frame.pending = frame.pending[1:]
candidate := path.Join(resolved, segment)
@@ -177,12 +207,22 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
if err != nil {
return "", err
}
if info.Mode()&fs.ModeSymlink == 0 {
resolved = candidate
if operations.readlink == nil || info.Mode()&fs.ModeSymlink == 0 {
resolved, resolvedInfo = candidate, info
if len(frames) == 1 {
if err := visit(info); err != nil {
return "", err
}
}
continue
}
if target, ok := completed[candidate]; ok {
resolved = target
resolved, resolvedInfo = target.path, target.info
if len(frames) == 1 {
if err := visit(resolvedInfo); err != nil {
return "", err
}
}
continue
}
if _, exists := active[candidate]; exists {
@@ -200,6 +240,7 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
root, pending := split(targetPath)
frames = append(frames, importLinkFrame{pending: pending, link: candidate})
resolved = root
resolvedInfo = nil
}
if resolved == "" {
resolved = "."
@@ -294,7 +335,11 @@ func resolveNativeImportPath(access *filesystemAccess, filesystem fs.ReadLinkFS,
if !fs.ValidPath(name) || !access.contains(name) {
return "", fs.ErrInvalid
}
return resolveImportLinkPath(name, importLinkOperations{
return resolveImportLinkPath(name, nativeImportLinkOperations(access, filesystem))
}
func nativeImportLinkOperations(access *filesystemAccess, filesystem fs.ReadLinkFS) importLinkOperations {
return importLinkOperations{
lstat: func(candidate string) (fs.FileInfo, error) {
// Ancestors of a multi-component root are resolution prefixes, not
// selected targets. Complete paths and link targets remain contained.
@@ -308,13 +353,14 @@ func resolveNativeImportPath(access *filesystemAccess, filesystem fs.ReadLinkFS,
if target == "" || strings.HasPrefix(target, "/") {
return "", errImportPathOutsideRoot
}
targetPath := path.Clean(path.Join(path.Dir(candidate), target))
if !fs.ValidPath(targetPath) || !access.contains(targetPath) {
targetPath := path.Dir(candidate) + "/" + target
clean := path.Clean(targetPath)
if !fs.ValidPath(clean) || !access.contains(clean) {
return "", errImportPathOutsideRoot
}
return targetPath, nil
},
})
}
}
func isImportLinkCycle(err error) bool {

View File

@@ -340,40 +340,77 @@ func globStartingCandidates(access *filesystemAccess, base, pattern string, segm
prefixAccess.rootPath, prefixAccess.root = "", nil
}
candidate := selectedImportCandidate{path: normalizedImportCandidatePath(access, start), accessPath: start, site: site}
consumed := 0
for index, segment := range segments {
literals := make([]string, 0, len(segments))
for _, segment := range segments {
literal, patterned := globLiteralSegment(segment)
if patterned {
break
}
lexical, lexicalErr := resolveLiteralImportSelector(&prefixAccess, candidate.path, literal)
parentAccess := candidate.accessPath
if literal == ".." {
target, err := prefixAccess.importEntryTarget(parentAccess, nil, true)
if err != nil {
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob parent directory could not be inspected")}
}
if target.identity != "" {
parentAccess = target.identity
}
}
physical, physicalErr := resolveLiteralImportSelector(&prefixAccess, parentAccess, literal)
if lexicalErr != nil || physicalErr != nil {
return nil, 0, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob prefix is outside the selected namespace")}
}
next, missing, diagnostics := explicitGlobCandidate(&prefixAccess, base, lexical, physical, site, index == len(segments)-1)
if len(diagnostics) != 0 {
return nil, 0, diagnostics
}
consumed++
if missing {
return nil, consumed, nil
}
if !globResolutionPrefixAllowed(access, next.accessPath) {
return nil, 0, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob prefix is outside the configuration root")}
}
candidate = next
literals = append(literals, literal)
}
if len(literals) != 0 {
baseTarget, err := prefixAccess.importEntryTarget(start, nil, true)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, len(literals), nil
}
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob starting directory could not be inspected")}
}
if !baseTarget.dir {
return nil, len(literals), nil
}
resolvedBase := baseTarget.identity
if resolvedBase == "" {
resolvedBase = start
}
operations := hostImportLinkOperations(&prefixAccess)
if access.native != nil {
if links, ok := access.native.(fs.ReadLinkFS); ok {
operations = nativeImportLinkOperations(&prefixAccess, links)
} else {
operations = importLinkOperations{lstat: prefixAccess.stat}
}
}
index := 0
operations.visit = func(physical string, info fs.FileInfo) error {
literal := literals[index]
lexical, err := resolveLiteralImportSelector(&prefixAccess, candidate.path, literal)
if err != nil {
return err
}
accessPath := physical
if access.native != nil && literal != ".." {
// Keep native source spelling; resolved identities guide traversal.
accessPath = access.join(candidate.accessPath, literal)
}
// Retain filesystem access errors as well as link inspection errors.
if access.native != nil {
if _, err := prefixAccess.canonical(accessPath); err != nil {
return err
}
} else if _, err := prefixAccess.stat(physical); err != nil {
return err
}
if !globResolutionPrefixAllowed(access, physical) {
return errImportPathOutsideRoot
}
if index < len(segments)-1 && !info.IsDir() {
return fs.ErrNotExist
}
candidate = selectedImportCandidate{path: normalizedImportCandidatePath(access, lexical), accessPath: accessPath,
label: relativeImportLabel(access, base, lexical), site: site}
index++
return nil
}
_, err = resolveImportLinkPathFrom(resolvedBase, strings.Join(literals, "/"), operations)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, len(literals), nil
}
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob prefix could not be inspected")}
}
}
consumed := len(literals)
if !access.contains(candidate.accessPath) || !access.contains(candidate.path) {
return nil, 0, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob discovery starts outside the configuration root")}
}

View File

@@ -7,7 +7,7 @@ import (
"testing"
)
func TestHostImportsResolveParentsInsideLinkTargets(t *testing.T) {
func TestImportsResolveParentsInsideLinkTargets(t *testing.T) {
root := canonicalTestPath(t, t.TempDir())
writeImportFile(t, root, "external/b/unit/marker", "")
writeImportFile(t, root, "external/a/shared/part.yml", "value: wrong\n")
@@ -41,6 +41,19 @@ func TestHostImportsResolveParentsInsideLinkTargets(t *testing.T) {
}
}
}
if !absolute {
// A fully literal native glob must retain filesystem link semantics
// while its prefix cursor uses resolved coordinates internally.
writeImportFile(t, root, "app/main.yml", "config: {imports: [{glob: /external/alias/part.yml, required: true}]}\n")
namespace := newNativeNamespace("fixture", os.DirFS(root))
result, err := testLoad[map[string]string](filesystemFile(namespace, "app/main.yml"), Options[map[string]string]{Imports: true})
if err != nil {
t.Fatal(err)
}
if result.Config["value"] != "intended" || result.Inspection.Sources()[1].Path != "external/alias/part.yml" {
t.Fatalf("native result=%#v", result.Config)
}
}
if err := os.Remove(alias); err != nil {
t.Fatal(err)
}