Skip to content

Migrate DefaultProject to immutable snapshots - #14133

Open
ayush-builds-stuff wants to merge 9 commits into
apache:masterfrom
ayush-builds-stuff:issue-13461-project-state
Open

ayush-builds-stuff wants to merge 9 commits into
apache:masterfrom
ayush-builds-stuff:issue-13461-project-state

Conversation

@ayush-builds-stuff

@ayush-builds-stuff ayush-builds-stuff commented Nov 26, 2026 •

Copy link
Copy Markdown

Contributes to #13461.

Related to #13467.

Summary

This PR establishes the first incremental project-state foundation for the Project Builder inversion described in #13461.

  • Introduce MutableProject as the stable project identity and owner of:
    • the current immutable Project snapshot;
    • source roots;
    • attached artifacts;
    • project properties.
  • Turn MavenProject into a compatibility façade over the shared MutableProject state for the migrated fields.
  • Make DefaultProject a true immutable v4 snapshot with no reference to MavenProject.
  • Remove the previous updateProject() and newSnapshot() refresh flow.
  • Preserve distinct identity for projects with identical coordinates and for temporary forked projects.
  • Share the project registry across derived session views.
  • Keep transformed v3 and v4 models consistent by replacing the immutable snapshot through the session.
  • Add compatibility, identity, concurrency, fork-lifecycle, and transformer regression tests.

Project-state design

                         immutable snapshot
MutableProject --------------------------------> Project / DefaultProject
      ^
      |
      +---- MavenProject compatibility façade
      |
      +---- ProjectManager build-time mutations

MutableProject is the stable internal identity for a project. It contains an AtomicReference for the current immutable snapshot and directly owns the mutable build-time state that is intentionally outside the Project snapshot.

MavenProject and DefaultProjectManager operate on the same holder:

  • MavenProject reads project identity from the current snapshot and delegates source roots, attached artifacts, and properties to MutableProject.
  • DefaultProjectManager reads and mutates the same build-time state.
  • DefaultProject stores v4 values directly and does not retain a legacy MavenProject reference.

DefaultSession maintains identity-based mappings between each exact MavenProject instance, its MutableProject holder, and the immutable snapshots produced from that holder. Derived session views share this registry, so withContext(), repository derivation, and similar operations retain project identity.

Temporary forked projects are intentionally registered by object identity for the lifetime of the session. This prevents coordinate collisions and ensures that forked clones do not share state with their originating projects.

Transitional compatibility boundary

The v3 project builder remains unchanged in this PR.

LegacyProjectAdapter isolates the initial conversion from the legacy builder output into an immutable v4 DefaultProject snapshot. Moving project-building ownership into maven-impl will be handled by later incremental PRs under #13461.

ProjectTransformerDispatcher is handled explicitly because transformers can produce a new model after the initial snapshot has been created. The session installs a new immutable snapshot, updates the holder and reverse mappings, and keeps the legacy MavenProject model consistent.

This PR does not attempt to migrate every legacy MavenProject model mutation. Its scope is the project-state foundation and the mutable build-time state identified in #13461.

Validation

  • maven-core: 940 tests, 0 failures, 0 errors, 1 skipped
  • maven-impl: 962 tests, 0 failures, 0 errors, 4 skipped
  • Focused session and transformer tests: 15 tests passed
  • Maven CLI and legacy embedder reactor build succeeded
  • Checkstyle passed
  • Spotless passed
  • git diff --check passed

———

To make clear that you license your contribution under the
Apache License Version 2.0, January 2004 (https://www.apache.org/licenses/LICENSE-2.0),
check one of the following:

@gnodet-bot gnodet-bot 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.

The refactoring cleanly replaces the mutable MavenProject state model with immutable DefaultProject snapshots, with a well-structured concurrent backing store (ProjectsHolder) and atomic updates via AtomicReference. The overall approach is sound and the test coverage is solid.

Two observations worth noting:

Forked/temporary project lifecycle — The old code had an explicit guard comment (removed in this PR) explaining why session::getProject couldn't be used for forked projects (which were temporary clones). The new code uses session::getProject via the IdentityHashMap-backed ProjectsHolder. The identity semantics prevent GAV collisions correctly, and the new test forkedProjectDoesNotShareItsExecutionProjectsHolder validates distinct identity and reverse mapping. Worth being aware that temporary forked clones registered in the IdentityHashMap will accumulate for the session's lifetime — this is intentional and acceptable, but worth documenting.

updateProject() atomicity — The method performs a synchronized getMavenProject() lookup followed by a separate AtomicReference.updateAndGet() CAS. These two operations are not performed as a single atomic unit. This is a pre-existing design constraint of the backing structure, and in practice the MutableProject identity is stable once registered, so this is unlikely to cause issues. A short comment at the method level acknowledging this assumption would help future maintainers.

Both are observations, not blockers.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot 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.

Thank you for this PR — the MutableProject identity holder and ProjectRegistry are solid foundations. However the direction of the dependency between MavenProject and MutableProject is inverted relative to the goal described in #13461.

The problem

Right now DefaultProject is an immutable snapshot copied from MavenProject at construction time. MavenProject remains the authoritative mutable state store. updateProject() re-reads from it after each mutation. This means:

  • MavenProject is not demoted — it stays the source of truth
  • Any v3 plugin mutating MavenProject directly (outside DefaultProjectManager) produces stale snapshots
  • Future PRs cannot build incrementally toward the inversion described in #13461 because the dependency arrow still points the wrong way

The goal (from #13461)

The target design is:

MutableProject          ← single source of truth (holds v4 state + build-time mutable state)
  ↑ reads              ↑ writes via ProjectManager
MavenProject (façade)   Project (immutable snapshot of v4 state)

Concretely:

  • MutableProject owns the mutable build-time state: source roots, attached artifacts, properties
  • MavenProject becomes a thin façade: reads delegate to mutableProject.project() or mutableProject fields directly, writes go through ProjectManager
  • DefaultProject is a true immutable snapshot of v4 types — no reference back to MavenProject

Proposed fix — no Project API changes required

Move the mutable build-time state out of MavenProject and into MutableProject:

public final class MutableProject {
    private final AtomicReference<Project> snapshot;
    // Build-time mutable state — not part of the immutable Project snapshot
    final List<SourceRoot> sourceRoots = new CopyOnWriteArrayList<>();
    final List<Artifact> attachedArtifacts = new CopyOnWriteArrayList<>();
    final Properties properties = new SynchronizedProperties();
}

Then MavenProject becomes a façade:

// reads
public String getGroupId()           { return mutableProject.project().groupId(); }
public List<Artifact> getAttachedArtifacts() { return mutableProject.attachedArtifacts; }

// writes — go through ProjectManager, which mutates MutableProject and re-snapshots
public void addAttachedArtifact(Artifact a) { projectManager.attachArtifact(this, ...); }

DefaultProject can then hold pure v4 types with no reference back to MavenProject, and updateProject() / newSnapshot() are no longer needed — mutations land directly in MutableProject.

This keeps the Project interface unchanged (source roots and properties stay on ProjectManager's surface, which is already the intended v4 access path) and is fully achievable within impl/.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot 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.

Following up on my earlier reviews — the main concern from the CHANGES_REQUESTED is fully addressed. MutableProject now owns mutable build-time state (source roots, attached artifacts, properties). MavenProject delegates to it. DefaultProject holds only a State record with no reference back to MavenProject. The dependency arrow now points in the correct direction as described in #13461.

Two concurrency issues and two documentation gaps remain.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot 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.

Following up on my earlier reviews — both concurrency issues are resolved.

  • sourceRoots() synchronization — ✅ fixed: synchronized with Collections.unmodifiableSet(new LinkedHashSet<>(sourceRoots)) snapshot copy under the monitor.
  • attachedArtifacts() synchronization — ✅ fixed: synchronized with List.copyOf(attachedArtifacts) snapshot copy under the monitor.
  • projectStates stale entry in replaceProjectModel — intentionally retained with an explanatory comment ("Retain old snapshots so callers holding them can still resolve the stable project identity"). This is a deliberate design decision, not an oversight; memory cost is bounded to the number of model replacements per build, which is typically very few. The existing inline comment stands as an observation.

No new blocking issues introduced by this commit. LGTM.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@github-actions

This comment has been minimized.

Remove the generic type parameter <A> from MutableProject by using
org.apache.maven.api.Artifact as the concrete attached-artifact type.
This eliminates the dependency inversion that required the type
parameter to avoid a cyclic dependency between maven-core and
maven-impl.

The v4 path (DefaultProjectManager) is simplified — attached artifacts
are stored and returned directly without v3↔v4 conversion. The legacy
v3 path (MavenProject) takes on the conversion burden through
session.toArtifact() which also resolves paths from ArtifactManager,
ensuring getAttachedArtifacts() returns v3 artifacts with files set.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@gnodet-bot gnodet-bot 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.

Following up on my earlier review — the previous findings are all addressed, and the new commit introduces a focused change: removing the <A> type parameter from MutableProject to avoid a cyclic dependency between maven-core and maven-impl.

Three observations on the new commit.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

- Add instanceof guard in getAttachedArtifacts() to make the
  ProducedArtifact invariant explicit instead of a bare cast.
- Guard getAttachedArtifacts() against uninitialized MutableProject
  (e.g. cloned projects) by short-circuiting on empty list.
- Restore behavioral notes in addAttachedArtifact() javadoc about
  the never-thrown exception and replacement semantics.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@gnodet-bot gnodet-bot 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.

Following up on my earlier review — two of the three findings are fully addressed, one partially.

  • Type invariant (instanceof guard) — ✅ addressed: explicit IllegalStateException with the artifact description replaces the bare cast.
  • Javadoc regression — ✅ addressed: behavioral notes restored (replacement semantics, never-thrown exception declared). The since Maven 3.0.x detail was trimmed, which is acceptable.
  • NPE on unregistered MavenProject.getAttachedArtifacts() — ⚠️ partially addressed — see inline comment.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot 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.

Following up on my earlier review — the new commit makes the path assertions in MavenProjectTest platform-independent (Path.of(...).endsWith(Path.of(...)) instead of String.endsWith()). That is a correct cross-platform fix.

The open finding from the previous review remains unresolved.

NPE on getAttachedArtifacts() for deepCopy clones with non-empty artifacts — ⚠️ still open. See the inline comment below for the specific scenario and fix options.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

…oject is not registered in session

addAttachedArtifact(), getAttachedArtifacts() and setAttachedArtifacts() now guard against
an uninitialized MutableProject (project has not been registered via DefaultSession.getProject()
yet) by falling back to a legacy artifact list. When the project is later registered in the
session, any pre-accumulated legacy artifacts are migrated into MutableProject.

This fixes test failures in DefaultMavenTest, ReactorReaderTest, MavenLifecycleParticipantTest,
ConsumerPomArtifactTransformerTest and LifecycleExecutorTest where bare MavenProject instances
are created and used without going through a full Maven session.
@gnodet

gnodet commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Fixed the CI failures with a commit on the branch.

Root cause: addAttachedArtifact(), getAttachedArtifacts() and setAttachedArtifacts() unconditionally called mutableProject.project(), which throws NPE when the project hasn't been registered in a session yet (i.e. when DefaultSession.getProject(MavenProject) hasn't been called for it). This affected:

  • Tests that create bare new MavenProject() and call artifact methods directly (DefaultMavenTest, ReactorReaderTest, ConsumerPomArtifactTransformerTest, LifecycleExecutorTest)
  • Full-build tests (MavenLifecycleParticipantTest) where ConsumerPomArtifactTransformer.injectTransformedArtifacts() is called before the project is registered in the v4 session

Fix: Guard all three methods with mutableProject.projectOrNull() != null. When the project is uninitialized, fall back to a legacyAttachedArtifacts list (restoring the old behavior). When the project is later registered in the session via DefaultSession.getProject(), any accumulated legacy artifacts are migrated into MutableProject and the legacy list is cleared.

gnodet and others added 2 commits December 1, 2026 17:49
Add checkstyle.violation.ignore=FileLength to maven-core pom (same pattern
as maven-impl and maven-model, which also have files exceeding 2000 lines).
Trim verbose Javadoc added in previous commit to minimize the overage.
The v3→v4→v3 artifact conversion in addAttachedArtifact() lost the
original v3 artifact instance, breaking two things:

1. TransformedArtifact (consumer POM) lost its lazy file regeneration,
   causing NoSuchFileException after clean deleted the temp file.

2. Plain attached artifacts lost object identity, breaking
   DefaultArtifactDeployer.relatedMetadata sharing and causing
   attached artifacts to get different snapshot build numbers (mng-1021).

Fix by caching original v3 artifacts keyed by v4 artifact key and
returning them from getAttachedArtifacts(). Build the aether artifact
without calling getFile() to avoid triggering lazy side effects.
Route legacy artifact migration through MavenProject.addAttachedArtifact()
so the cache is populated during session registration.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
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.

3 participants