Skip to content

Migrate DefaultProject to immutable snapshots - #14133

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

ayush-builds-stuff wants to merge 3 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.

Comment on lines +108 to +110
public Collection<SourceRoot> sourceRoots() {
return Collections.unmodifiableSet(sourceRoots);
}

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.

⚠️ Concurrency gap: sourceRoots() is not synchronized but replaceSourceRoot() and setSourceRoots() are.

replaceSourceRoot() holds this as a monitor and executes sourceRoots.clear() then sourceRoots.addAll() — two separate write operations. A concurrent reader calling sourceRoots() between clear() and addAll() observes an empty collection. The synchronized on the mutators implies a stronger contract than the CopyOnWriteArraySet alone would provide, but sourceRoots() bypasses the lock entirely.

The same gap applies to attachedArtifacts() (line 129) with respect to setAttachedArtifacts().

Fix: either add synchronized to both readers, or drop the synchronized on the multi-step mutators and use a plain CopyOnWriteArraySet for iteration-safe reads while accepting that bulk mutations are not atomic:

Suggested change
public Collection<SourceRoot> sourceRoots() {
return Collections.unmodifiableSet(sourceRoots);
}
@Nonnull
public synchronized Collection<SourceRoot> sourceRoots() {
return Collections.unmodifiableSet(sourceRoots);
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 46842f6. sourceRoots() now synchronizes with the mutators and returns an ordered snapshot captured while holding the monitor. This avoids exposing both the intermediate clear() state and a live view after the lock is released. Regression coverage was added.

Comment on lines +129 to +130
public List<A> attachedArtifacts() {
return Collections.unmodifiableList(attachedArtifacts);

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.

⚠️ Same concurrency gap as sourceRoots(): attachedArtifacts() is not synchronized.

setAttachedArtifacts() does clear() then addAll() under the monitor. A concurrent reader calling attachedArtifacts() between those two steps sees an empty list.

Suggested change
public List<A> attachedArtifacts() {
return Collections.unmodifiableList(attachedArtifacts);
@Nonnull
public synchronized List<A> attachedArtifacts() {
return Collections.unmodifiableList(attachedArtifacts);
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 46842f6. attachedArtifacts() now synchronizes with the bulk mutator and returns a List.copyOf(...) snapshot captured under the same monitor. This prevents readers from observing the intermediate clear()/addAll() state. Regression coverage was added.

Comment on lines +209 to +212
requireNonNull(projects.legacyProjects.get(mutableProject), "project is not associated with session")
.setModel(new org.apache.maven.model.Model(model));
return replacement;
}

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.

💡 projectStates stale entry accumulation in replaceProjectModel. The old project key is left in projectStates after replacement (line 209 adds replacement, but there is no projectStates.remove(project)). This is intentional if callers that hold a reference to the old DefaultProject should still be able to route to the MutableProject via getMutableProject(old). However, over repeated ProjectTransformer passes, projectStates accumulates one stale entry per replacement per project. If that is an acceptable trade-off (e.g. because transformer passes are few), add a brief comment explaining the deliberate retention; otherwise remove the old key:

Suggested change
requireNonNull(projects.legacyProjects.get(mutableProject), "project is not associated with session")
.setModel(new org.apache.maven.model.Model(model));
return replacement;
}
DefaultProject replacement = ((DefaultProject) project).withModel(model);
mutableProject.replace(project, replacement);
projects.projectStates.remove(project); // remove stale entry
projects.projectStates.put(replacement, mutableProject);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The retention is intentional. Callers holding an older immutable snapshot must still be able to resolve the project’s stable MutableProject identity and legacy MavenProject. I added a comment documenting that trade-off in 46842f6; the existing session test verifies that both the old and replacement snapshots retain their reverse mapping.

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

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.

2 participants