Mutating Shared State

Topics Covered

Why Shared State Breaks Quietly

References, not copies

Why assistants produce aliasing bugs

Why tests often miss them

What the interviewer sees

An example in Python

An example in TypeScript

An example in Java

The pattern in all three

A drill for spotting shared state

Shared state and the twist

Shared state across calls

Why it matters more with assistants

A sample exchange

Summary

Saying it in one sentence

Many of the most confusing bugs in assistant code come from shared mutable state: two parts of a program holding references to the same object, and one of them changing it when the other does not expect it. The code often reads correctly line by line. Each function does what it says. The bug lives in the relationship between them, which is why it is easy to miss in review and hard to find when it appears.

This lesson covers how references and copies work in the three course languages, the shapes in which aliasing bugs usually appear, how to probe for them and how to fix them cleanly.

Two names, one object. A change through either is visible through both.

References, not copies

In Python, JavaScript, TypeScript and Java, variables that hold lists, dictionaries, arrays, maps, sets and objects hold references. Assigning one variable to another copies the reference, not the object. Passing an object to a function passes a reference. Storing an object in a list stores a reference. Returning an object from a function returns a reference.

This is efficient and usually what you want. It becomes a problem when one holder of the reference changes the object and another holder expects it to stay the same.

Numbers, strings and booleans behave differently in practice, because they cannot be changed in place in any of these languages. Operations on them produce new values. Tuples in Python and frozen objects or records in TypeScript and Java are similar. Only mutable containers and objects create aliasing problems.

Why assistants produce aliasing bugs

Assistants produce aliasing bugs for several reasons. They often write code that builds results by modifying a working object and then appending it somewhere, which is correct only if a fresh object is created each time. They reach for in place methods, such as sort, reverse or push, because those are common in the code they learned from, without checking whether the caller expects the input to be left alone. They return internal state directly, which is shorter than returning a copy. And they use idioms, such as a mutable default argument or a list multiplication to create rows, that look natural and share an object unexpectedly.

Why tests often miss them

Aliasing bugs often survive the visible tests. A test that calls a function once and checks the result does not see that the input was modified. A test that builds a structure and checks it at the end does not see that two entries are the same object, unless it changes one and checks the other. A test that calls a function with an explicit argument does not see a shared default. Only tests that check the input after the call, call the function twice or modify a returned value reveal these bugs.

What the interviewer sees

Aliasing bugs are a favourite in code review rounds because they test whether the candidate understands the language, not just the algorithm. Spotting one, explaining it in a sentence and fixing it with the right kind of copy, or by not mutating at all, is a strong signal. Missing one, and then spending ten minutes debugging a test that fails for reasons that seem unrelated, is a common way to lose a round.

An example in Python

diff
1+def add_tag(post, tag):
2+    tags = post["tags"]
3+    tags.append(tag)
4+    return {**post, "tags": tags}

The function seems to return a new post with the tag added, leaving the original alone. The spread creates a new outer dictionary. But tags is the same list as the original post's tags, so append modifies the original post too. Any caller that kept the original post now sees the extra tag.

An example in TypeScript

diff
1+function withDefaults(opts: Options): Options {
2+  const out = opts;
3+  out.retries ??= 3;
4+  out.timeout ??= 1000;
5+  return out;
6+}

The name suggests a new options object with defaults filled in. But out is opts, so the caller's object is modified. If the caller reuses the same options object for several calls, and later checks whether retries was set explicitly, it will see the default as if the caller had set it.

An example in Java

diff
1+class Cart {
2+    private final List<Item> items = new ArrayList<>();
3+    List<Item> getItems() { return items; }
4+}

getItems returns the internal list. Any caller can add or remove items without going through the cart's methods, bypassing whatever checks those methods do. A caller that sorts the returned list for display reorders the cart itself.

The pattern in all three

In each case, a value that looked like a fresh object, or like a read only view, was actually shared with something else. The fix is the same in principle: either copy before changing, or do not change at all. The rest of the lesson shows how to decide which, and how to find these bugs quickly.

A drill for spotting shared state

For each of the next ten assistant diffs you review, list every object that is changed in place: appended to, assigned into, sorted, reversed, cleared or updated. For each, ask who else holds a reference to it. If the answer is the caller, a stored structure or a later iteration of a loop, check that the sharing is intended. After ten diffs, this question will start asking itself.

Shared state and the twist

The twist often adds a feature that reuses existing data: an undo, a history, a preview, a comparison between two versions, a second consumer of the same results. Each of these assumes that old values stay as they were. Code that mutated freely before the twist may have worked, because nothing kept the old values. After the twist, the same mutation breaks the new feature. When the twist asks for anything that remembers the past, check every in place change in the code you are building on.

Shared state across calls

Some bugs need two calls to appear. The first call leaves something behind, a filled default, a cached result, a changed module level list, and the second call sees it. Visible tests that run each case in a fresh process never see this. Hidden checks that run many cases in one process do. If a function has any state that survives between calls, ask whether that state is meant to be there and whether the second call could be affected by the first.

Why it matters more with assistants

When you write code yourself, you usually know which objects are shared because you created them. When an assistant writes the code, you did not see the decisions. It may have reused an object to save a line, or returned a field because that was shorter. Reviewing assistant code means reconstructing those decisions, and asking who else holds this object is the question that does it.

A sample exchange

Interview Dialogue

CandidateBefore I accept this, the helper now sorts its argument instead of a copy. Who calls it?
CandidateTwo callers. The first passes a fresh list, so it is fine. The second passes the cart's own list, which is then shown in insertion order on the receipt.
CandidateSo this change would reorder receipts. I will keep the copy, or use sorted.

The candidate did not need to run anything. Asking who else holds the object found the bug.

Summary

Variables, arguments, stored entries and return values share objects. Assistants create aliasing bugs through in place methods, reused working objects, returned internals and shared defaults. Visible tests rarely look for them, so you have to.

Saying it in one sentence

When you find an aliasing bug, name it in one sentence: the new dictionary shares the tags list with the original, so append changes both. That sentence names the object, the two holders and the operation. It is all the interviewer needs.

Then fix it and move on.

Assignment copies references, not objects

In all three course languages, assigning, passing, storing or returning a list, map, array or object shares the same object. Only immutable values such as numbers, strings and tuples are safe to share without thinking.