spring-projects / spring-projects/spring-ai

`Document.mutate()` shares the metadata map with the original document

Open Beginner friendly
#6,910 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

status: waiting-for-triage
Dominant language
Java
Stars
9.5k
Forks
2.9k
Avg merge
1d 10h
Merged PRs (30d)
5

Description

Bug description

Document.mutate() is documented as "allowing selective modification without altering the original", but it passes the document's internal metadata map into the new builder by reference:

public Builder mutate() {
    return new Builder().id(this.id).text(this.text).media(this.media).metadata(this.metadata).score(this.score);
}

Builder.metadata(String key, Object value) then calls put directly on that map, so mutating the builder mutates the original Document's metadata.

Environment

  • Spring AI 2.0.2-SNAPSHOT, main at 0933bd0
  • Module: spring-ai-commons
  • Class: org.springframework.ai.document.Document

Steps to reproduce

Document original = Document.builder().text("Original text").metadata("original", "value").build();

Document mutated = original.mutate().metadata("new", "metadata").build();

// fails: original now contains the "new" key as well
assertThat(original.getMetadata()).doesNotContainKey("new");

Expected behavior

mutate() seeds the builder with a copy of the metadata map (new HashMap<>(this.metadata)), so builder modifications never leak into the original document. Note that mutate() for the other fields already behaves this way because they are immutable or reassigned on build.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in the Document class in the spring-ai-commons module, focusing on mutate() and Builder.metadata(String, Object), then reproduce the issue with the example in the report. Done means builder metadata changes no longer appear in the original document, while the mutated document retains the new metadata.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
88/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.