Skip to navigation

Go Module Graph Pruning: Explain Indirect Dependencies With Claude Code

In short: Find why Go records indirect requirements and how graph pruning changes what the module command loads.

Published 22 min read
On this page

Direct answer

An // indirect marker in go.mod records how a requirement entered your build list, not a suggestion that you delete the line. Go chooses one version per module using minimal version selection, which picks the highest version required anywhere in the module graph as the build-list version for that module. Starting with modules that declare Go 1.17 or later, graph pruning trims what the tooling loads to the immediate requirements of pruned modules, and lazy loading fetches more graph data on demand when it is actually needed. The concrete win is a go.mod that stays readable because the tooling no longer has to record every transitive requirement of every dependency. The concrete loss is that the // indirect comment on its own does not tell you which path pulled a module in, so a human or an agent reading the file still needs go mod graph or go mod why to explain a specific entry.

Ask Claude Code to explain a marker using the graph commands, not to clean the file by removing transitive-looking lines. A marker removal that leaves a real requirement unsatisfied breaks the build, and a marker kept without understanding it teaches nobody anything. The review unit here is the graph, and the artifact worth keeping is a short explanation of why each surprising entry exists.

Why an unexplained requirement costs real time

Three situations turn an indirect entry into a time sink. A security review asks which dependency introduced a module with a known advisory, and nobody can answer from go.mod alone because the file lists requirements without their paths. An upgrade leaves a module pinned at a version nobody recognizes, and the team argues about whether a line is stale before anyone runs the graph command. A new contributor deletes a line that looked redundant, the build fails in a way that blames the wrong package, and the revert costs an afternoon.

None of these are tooling defects. They are the predictable result of treating go.mod as a flat list when it is a compressed view of a directed graph. Minimal version selection and graph pruning are the two rules that decide what appears in the file, so reading the file well means knowing both. The cost is paid in review meetings and in CI round trips, not in a single dramatic failure.

There is a revert advantage in this area too. Explanations live in a comment or a short design note, and graph commands are read-only, so exploring the graph does not mutate the repository. That makes it a good fit for a Claude Code session: the agent can run the read-only commands, propose a tidy, and a reviewer can check the resulting diff against the graph rather than against intuition.

Evidence and its limits

Official, F013: The Go Modules Reference states that Go uses minimal version selection to choose the highest version required anywhere in the module graph as the build-list version for each module. The minimal version selection anchor documents the selection rule in detail. This describes how a version is chosen. It is not a safety ranking of the selected versions, and MVS says nothing about whether the chosen version is free of advisories.

Official, F014: The same reference documents that for modules declaring Go 1.17 or later, graph pruning limits the graph to the immediate requirements of pruned modules, while lazy loading can fetch more graph data on demand. The go.mod reference records how the go directive in go.mod participates in this behavior. The exact graph also depends on non-pruned modules and on your explicit requirements, so a one-sentence summary is a simplification rather than a complete rule.

Official, versioning context: Semantic Versioning 2.0.0 defines the version scheme Go modules build on, which is why “highest version” has a defined meaning rather than being a string comparison.

Official, agent loop: Claude Code best practices recommends giving the agent a check that returns pass or fail. For graph work the check is go build ./... plus go mod tidy producing an empty diff. Claude Code common workflows covers running an edit against a command in a loop.

No claim here depends on a specific Go patch release beyond the 1.17 pruning boundary the reference itself states. Registry behavior, proxy caching, and vendoring are out of scope.

Minimal version selection basics

Minimal version selection answers one question: given every module that is reachable and every version each one requires, which single version of each module goes on the build list. The rule is to take the highest version that any reachable module requires. The word “minimal” refers to doing the least work needed to satisfy every requirement, not to picking older versions.

A short example makes the rule concrete. Suppose your module requires example.com/dep at v1.2.0, and a tool you also depend on requires example.com/dep at v1.4.0. The build list gets v1.4.0, because that is the highest version required anywhere in the graph. Nothing in MVS looks at changelogs, advisories, or your preference. It takes the maximum.

Module in the graph Requires example.com/dep Version that wins
your module v1.2.0 not alone
example.com/tool v1.4.0 v1.4.0 (highest required anywhere)
example.com/lib v1.3.1 superseded by v1.4.0

Reading the table top to bottom, the winner is the maximum of the required versions, which is the MVS rule in one line. The practical consequence is that upgrading one dependency can raise another module’s selected version without you editing it, because a new requirement entered the graph at a higher version. That surprises teams who expect each require line to be independent.

Read the require graph

Two read-only commands turn go.mod back into a graph. go mod graph prints one edge per line, in the form module@version requires module@version. go mod why <module> prints the shortest import path from your package to a given module, which is the answer to “why is this here”.

bash
go mod graph
go mod why example.com/indirect/dep

go mod graph output is long on a real project, so treat it as raw material rather than something to read end to end. Searching it for a specific module answers a specific question. go mod why is the tool for the single surprising entry that prompted the investigation, because it names the import chain instead of only naming the module.

Claude Code can run both commands and summarize the path to a target module. The summarization is where review matters. A path that the agent reports should be verifiable by re-running go mod why yourself, and the official best-practices guidance favors checks with unambiguous pass or fail results over prose summaries.

Understand graph pruning

Graph pruning changes what the tooling loads by default. For a module that declares Go 1.17 or later, the module graph is limited to the immediate requirements of the pruned modules, so go.mod no longer has to list the full transitive closure of every dependency. Modules that declare an earlier Go version are not pruned, and their requirements are loaded the older way.

Graph view What it includes What the tooling loads by default
Unpruned (pre-1.17 module) Full transitive requirements of the module The whole module graph
Pruned (Go 1.17+) Immediate requirements of pruned modules Only what is needed for the build, with more fetched on demand
Your explicit requires Whatever you wrote in go.mod Loaded directly, not pruned away

The distinction that matters is that pruning is not dependency minimization. Pruning changes what the tooling reads from the graph up front; it does not remove a module that your build genuinely needs. A pruned graph can still contain many modules, and a non-pruned dependency can pull a large subgraph back in. Treat “the graph is pruned” as a statement about loading behavior, not about how small your dependency set is.

Lazy loading is the mechanism that makes pruning practical. When a command needs graph information that was pruned away, it fetches that information on demand rather than requiring it to be present in go.mod from the start. The result is fewer lines in the file and more network fetches in specific situations, which is a trade rather than a free improvement.

Connect lazy loading to go.mod

Because more of the graph is fetched on demand, go.mod records the requirements needed to make the build work and to keep the graph consistent, and some of those are transitive requirements of your direct dependencies. Those transitive requirements are the lines marked // indirect.

The go directive at the top of go.mod sets the pruning behavior for your own module. Raising it to 1.17 or later opts the module into the pruned graph, which is why a version bump in that line can change the shape of a tidy. The reference documents this relationship between the go directive and graph pruning, so a change to that line is worth its own commit and its own explanation rather than riding along with an unrelated edit.

go.mod element Role in the graph Effect when changed
go 1.x directive Sets pruning behavior for the module Raising to 1.17+ enables the pruned graph
require (direct) A dependency your code imports Adds a graph edge you own
require ... // indirect A transitive requirement kept for graph consistency Present to satisfy MVS, not because you import it
replace, exclude, retract Override or remove specific versions Changes selection without adding a new import edge

Read the table as a ownership map. Direct requires are yours to reason about. Indirect requires are bookkeeping that MVS and pruning produce. The override directives change selection and belong in their own review.

Interpret indirect markers

An // indirect marker means the requirement is not imported directly by your module’s packages. It is recorded because the build list needs it, either as a transitive requirement of a dependency or, in some cases, because a dependency failed to list its own requirement and Go recorded it on your behalf to keep the graph consistent.

Three misreadings cause most of the trouble. Treating every // indirect as deletable, which breaks the build when the entry was load-bearing for graph consistency. Treating the marker as a provenance statement, when it records only that your module does not import the package directly. Treating go mod tidy as a version upgrade tool, when tidy aligns go.mod with the imports in your code and does not upgrade dependencies to their latest versions.

Marker or command What it tells you What it does not tell you
// indirect on a require Your module does not import this package directly Which dependency path introduced it
go mod why <module> The shortest import path to the module Whether the selected version has advisories
go mod graph Every requirement edge currently loaded Which edges pruning skipped by default
go mod tidy Aligns go.mod with actual imports Does not upgrade versions to latest

The fourth row is the one to internalize before running tidy as part of an upgrade. The Go reference is explicit that tidy aligns the file with imports; it is not a dependency update command. A tidy that appears to change many versions is usually revealing requirements that were already implied by the graph, not performing upgrades.

Review a proposed tidy diff

A tidy diff is reviewable when you know what a legitimate change looks like. The legitimate categories are: requirements added because your code now imports something new, requirements removed because nothing imports them anymore, indirect markers added or removed because the graph changed, and the go directive changing pruning behavior when you deliberately raised it.

Diff change Likely cause Action
A direct require added Your code imports a new package Confirm the import is intentional
A require removed Nothing imports it and nothing needs it for consistency Confirm no build tag or test needs it
A marker added to an existing require Pruning or a dependency change made it transitive for you Read go mod why for that module
A marker removed Your code now imports it directly Confirm the new import
Version changed without an edit to imports A dependency was upgraded elsewhere, and MVS selected higher Investigate which requirement raised it
go directive changed Someone raised the language version Give it its own commit and note pruning impact

Two defects to catch in review. A version change that nobody can explain is a finding to resolve before merge, because MVS selected a higher version for a reason and the reason should be nameable. A large tidy that rides along with a small feature change is a diff hygiene problem: split the tidy into its own commit so a revert of the feature does not revert the graph cleanup.

bash
go build ./...
go mod tidy
git diff -- go.mod go.sum

The pass condition for the session is concrete. The build succeeds, and a second go mod tidy run produces an empty diff, which shows the file is now consistent with the imports. The official best-practices guidance favors this kind of check over a prose report, because an empty diff is unambiguous.

Explain the resulting graph

After the tidy, the artifact worth keeping is a short explanation of the entries that surprised someone. A design note naming the three or four indirect requirements that prompted questions, each with the go mod why output that explains it, turns the next review into a lookup instead of an investigation. This is the same discipline as recording why a dependency exists, applied to the graph rather than to a lockfile.

For a specific indirect entry, the explanation has three parts: the module that requires it, the version MVS selected and why, and whether pruning affects whether it appears in your go.mod. A note that stops at “it is transitive” answers the question at the level that caused the confusion in the first place.

The same graph-reading discipline appears elsewhere in this batch. For the API-contract side of Go modules, the Go module compatibility guide covers keeping exported API changes inside an import path contract, and the Go workspace boundaries guide covers separating local development composition from each module’s published dependency contract.

The concrete win, loss, and implication

The concrete win is a go.mod a reviewer can actually read. With pruning, the file records what your build needs and the transitive requirements the graph requires for consistency, rather than the full closure of every dependency. That difference shows up in review meetings: fewer lines, and each line closer to something a person can explain.

The concrete loss is that a marker without a recorded explanation is still opaque. Pruning reduced the number of lines, and it did not attach a provenance note to any of them. When a security review or an upgrade question lands, the team still runs go mod why or go mod graph to answer it. The file is smaller, not self-documenting.

The practical implication is that graph questions deserve graph commands, not file edits. Teams that reach for go mod why before deleting a line spend less time reverting bad cleanups. Teams that clean go.mod by eye pay for it in build failures that blame the wrong package.

Graph structure is upstream of several risks this post deliberately leaves alone. What happens when a dependency is installed, including lifecycle behavior during download, is covered by the Claude Code dependency install side effects guide. The risk of an agent proposing a module that does not exist is covered by the Claude Code hallucinated packages guide, which is about blocking a nonexistent dependency before it reaches go.mod.

Reviewing the graph also touches verification habits with their own guides. Before calling a tidy done, ask what Claude Code verification requires, and prevent false success from passing tests when the check is a green build that does not exercise the changed path. A tidy that reformats the whole file alongside the graph change is the pattern the Claude Code overengineering guide warns about, so keep the diff to the graph.

The cost of a verification loop on a small change connects to Claude Code cost per verified change, which treats generated output and verified work as different units. An empty tidy diff is a cheap check that earns its place on every graph edit. On the review side, Claude Code code review covers what happens when faster generation outpaces the review that has to accept it.

Evidence map showing that go mod tidy aligns go.mod with imports and does not upgrade dependencies to their latest versions.
Editorial evidence map based on F013 and F014. Tidy aligns the manifest with imports; minimal version selection chooses the highest required version. Labels are the post author’s, not tool output.

Checklist before you explain or tidy a graph

Run this list before approving a graph change. Each row is a pass condition.

Check Pass condition If it fails
Surprising entry explained go mod why output recorded for each questioned module Run the command before editing
Version changes accounted for Every selected-version change has a named cause Investigate which requirement raised it
Markers not treated as deletions No line removed only because it read // indirect Restore it and check graph consistency
Tidy scope Tidy is its own commit, separate from features Split the commit before merge
Build check go build ./... succeeds Fix before merging
Idempotent tidy A second go mod tidy produces an empty diff Re-run tidy until stable
Pruning boundary A go directive bump is deliberate and noted Give the bump its own commit
Workflow from reading go mod graph and go mod why through interpreting indirect markers, reviewing a tidy diff, and confirming an idempotent tidy.
Editorial workflow based on F013 and F014. The sequence describes a reviewable routine for graph questions; it is not an official Go tooling command sequence.

Working with Claude Code on a graph question

Give the agent three inputs: the module whose entry prompted the question, the commands it may run, and the definition of done. Ask for go mod why output on the specific module and for a tidy diff as the verification step, and ask it to report the graph path rather than a summary judgment.

Reviewing the agent’s explanation is the reviewer’s job. The agent can run read-only graph commands and report paths, but deciding whether a selected version is acceptable for your project is a risk decision that needs your input. The Claude Code verification guide covers the review questions: what changed, what proves it, and what was not checked.

Tradeoff between a smaller pruned go.mod and the extra on-demand graph fetches plus the manual go mod why lookups a marker still requires.
Editorial tradeoff diagram based on F013 and F014. Pruning shrinks the loaded graph; the trade is on-demand fetching and the need to run graph commands for provenance.

What changes when you raise the go directive

Raising the go directive to 1.17 or later is the single edit most likely to change the shape of go.mod without touching a dependency. The directive controls whether your own module participates in the pruned graph, so moving it across the 1.17 boundary can add or remove indirect requirements on its own.

Change to the go directive Expected effect on go.mod Review question
Raise across 1.17 boundary Module opts into the pruned graph Did indirect requires change shape as expected?
Raise within same pruning regime Little graph-shape change Any version changes have a named cause
Lower below 1.17 Module returns to the unpruned graph Does the file grow with restored transitive entries?

Treat a directive bump as a graph-shape change, not a formatting change. The reference documents the relationship between the go directive and pruning, so the diff that follows a bump is explainable, but only if someone looks at it with pruning in mind. A bump that rides along with an unrelated feature commit is exactly the kind of change that becomes unexplainable two weeks later.

What tidy is and is not, precisely

Because tidy is the command most often misunderstood, it is worth stating its boundary once in plain terms. Tidy brings go.mod and go.sum into agreement with the packages your module actually imports, adding requirements that are needed and removing ones that are not, while keeping the graph consistent under minimal version selection.

Tidy does Tidy does not
Add requirements for packages your code imports Upgrade a dependency to its latest version
Remove requirements nothing imports anymore Downgrade a version to the lowest that satisfies the graph
Add or remove // indirect markers as the graph dictates Change which module a replace points at
Keep the graph consistent under MVS Audit selected versions for advisories

The right-hand column is where assumptions cause incidents. Teams that expect tidy to refresh versions run it as part of an upgrade and then cannot explain the version diff, because tidy did something different from what they assumed. Teams that expect tidy to be an advisory check treat a clean tidy as a security pass, which it is not. The command is a consistency operation, and every other expectation needs its own tool.

Data gap and future update

The pruning boundary in F014 is the Go 1.17 threshold the reference states, and this post does not claim behavior for module versions beyond what the reference documents. Projects mixing pruned and non-pruned dependencies see behavior that depends on that mix, and this post does not enumerate every combination.

No benchmark, build-time measurement, or network-fetch count is reported here, because none was measured. The reference describes lazy loading qualitatively; a future update that quantifies how many additional fetches a given graph shape causes would need a measurement pass with a fixed project and a fixed Go version. No such data was collected for this post.

Proxy and registry behavior is also out of scope. Caching, availability, and module mirror policy can change what a fetch returns without changing the graph rules described here.

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.

OpenAI-format agents have a separate route: One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. It is a different client and request format, not a workaround for Claude Code authentication. Check the free model list and eligibility notes before choosing an agent route, or read the quickstart for the request shape.

FAQ

Does go mod tidy upgrade my dependencies?

No. The Go reference is explicit that tidy aligns go.mod with the packages your code imports. It does not upgrade requirements to their latest versions. A tidy that appears to bump many versions is usually revealing requirements the graph already implied, not performing upgrades.

Can I delete a line marked // indirect?

Not on the basis of the marker alone. An indirect require is recorded because the build list needs it for graph consistency, and removing it can leave a real requirement unsatisfied. Run go mod why for the module first, then let go mod tidy decide what stays.

What is the difference between pruning and minimization?

Pruning changes what the tooling loads from the module graph by default, limiting it to the immediate requirements of pruned modules and fetching more on demand. It does not remove modules your build needs. A pruned graph can still be large, especially if a non-pruned dependency is present.

Why did a version change when I did not edit it?

Minimal version selection picks the highest version required anywhere in the graph. If a dependency you upgraded requires a shared module at a higher version, that module’s selected version rises even though you never edited its line. go mod graph shows which requirement raised it.

What proves a tidy is finished?

Two conditions. go build ./... succeeds, and a second go mod tidy produces an empty diff, showing the file is consistent with your imports. A build alone is not enough, because a file that tidy would change again is not yet stable.

This post is one of six language and build-system guides written together. The others cover the same explicit-boundary discipline in different ecosystems: Go Module Compatibility and Go Workspace Boundaries on the Go side, Cargo Feature Unification, Cargo Profile Boundaries, Cargo Build Scripts, and Cargo Workspace Inheritance on the Rust side.

The JVM and .NET posts cover version and variant selection. Gradle Constraints vs Dependencies covers fixing resolution without adding graph edges, and Gradle Capability Conflicts covers competing components. Gradle Variant Attributes covers matching consumers to artifacts, and Maven Optional Dependencies covers keeping transitive expectations explicit. NuGet Central Package Management covers cross-project version centralization.

For generated-code boundaries, the batch covers C# Source Generators, OpenAPI Generator Customization, and GraphQL Code Generator Client Presets. Framework maintenance is covered by Django Deprecation Runway, Rails Upgrade Sequence, and Angular Update Guide.

More from this batch

More Claude Code troubleshooting

Sources

Control checklist covering go mod why lookups, version-change accounting, tidy scope, build success, and an idempotent second tidy.
Editorial control checklist derived from F013 and F014. Passing the checklist shows the graph change was reviewed honestly; it does not audit advisory status of the selected versions.
Verdict that reading the graph with go mod why before editing beats deleting indirect lines by eye, keeping go.mod consistent with imports.
Editorial verdict based on F013 and F014. Graph questions are answered with graph commands; an indirect marker is metadata, not a deletion instruction.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
Claim $10 credit →