Borrowed data through a copy or a looser type: a shallow copy shares its parts, readonly dropped by an annotation (readonly-dropped) #141

Merged
sionzee merged 7 commits from shared-copies into main 2026-11-23 13:32:35 +01:00
Owner

Based on ways-out (#140), and contains it: the diff shown is this piece alone.

Two ways to change data that is not yours to change, both passing tsc strict, safe-ts check --idiomatic --deny-warnings and oxlint. Both came out of an outside audit of main; I confirmed each on the binary first.

function rename(order: Order): Order {
  const copy = { ...order, id: "new" };   // the form `no-param-mutation`'s own advice and oxlint steer you to
  copy.names.push("x");                    // the caller's list
  copy.meta.tag = "y";                     // the caller's object
  return copy;
}

type Limits = { retries: number };
export const LIMITS: Limits = Object.freeze({ retries: 3 });   // frozen at run time, writable by its type
raise(mut(LIMITS));                                             // compiles; TypeError when it runs

A shallow copy is a new object whose parts are still whoever's they were, and the checker followed only a list made of a single spread. And TypeScript lets readonly be dropped by any annotation, so a frozen object can be handed around as writable.

What changes

no-param-mutation follows shallow copies. An object spread, Object.assign({}, x), a destructured rest, a list with a spread among other elements, slice(), Array.from, and a copy a helper hands back are new objects whose own slots belong to the function and whose parts stay the parameter's. Changing a part through the copy is reported, and so is lending it with mut(...).

Lending a whole copy to a Mut parameter is reported only where the callee could write something the caller still holds. A field counts as shared when all of these hold:

  • the copy took it from the parameter and did not give it a value of its own;
  • something can be written through it, as far down as its type is written (a readonly T[] or ReadonlyMap of read-only parts is not shared);
  • the callee's parameter type has it;
  • the callee names it. A field the callee only gives a new value does not count.

The finding names the fields, and its help says to copy them or to write them read-only in the type. That last option turns a convention ("these lists are replaced whole, never changed in place") into something checked.

New rule readonly-dropped (error, with a quick fix). A value whose written type has a readonly property, given a place that can write it: an annotated binding, a declared return type, a field, an element of a typed list or map. Types are opened across files. Passing to a parameter that is not Mut is a read and stays silent.

Evidence

  • Held-out cases, written by the reviewer and not shown to the implementer.
    • Changing a part through a copy: 28 forms, all reported. 17 fine forms, all silent (a part copied too, a field given its own value, structuredClone, a Mut parameter, the function's own data).
    • Lending a whole copy: 18 harmful lends reported, 13 harmless ones silent. Three harmless ones are reported by design ("What stays coarse", below).
    • readonly-dropped: 14 of 14 forms reported, 7 fine forms silent.
  • Three rounds, and one fix of mine. The first version judged a whole-copy lend by the copy alone and read only types written in the same file (7 of my 14 forms). The second cost 2.7% of a check. The third added a summary for methods that read the receiver's declared class and so missed an override that changes the shared part; I fixed that by reading only a method no override can replace, as the newest rules already do.
  • What the new rule buys. With one frozen module constant typed writable, main catches 3 of 9 ways to write it. After the quick fix (Readonly<T> on the annotation), tsc refuses the direct writes and the lend, and this rule reports the next step: the constant handed out by a function, kept in a field, pushed into a list.
  • On an adopter's project (about 760 files):
    • no-param-mutation: 5 new findings, each a copy lent whole. Four are a hand-written clone of a large object that shares twelve lists, some on purpose, passed to a function that may change anything. One is a copy whose callee only reads the shared part (coarse, below).
    • readonly-dropped: 282, all of one kind: a frozen object literal declared under a writable type. None is a defect today. On a copy of one of its packages the fix command removed 272 of 273 in one run and surfaced four more of the same kind one step on (the implementer's measurement).
  • Soundness corpus: two classes added and closed (shallow-copy-shares-object, spread-list-shares-elements). 16 of 105 escape.
  • Cost: +0.97% instructions for a whole check of that project's largest entry, on top of #140 (17.31 to 17.48 billion, one thread, warm cache, callgrind; two runs of each binary agree to 0.01%). The second round cost 2.7%, nearly all of it readonly-dropped opening types across files; it now decides most sites in the file and remembers each pair of types for the pass. The work guard's allocation and memo-question counts each rose about 1%.

What turns red on upgrade

  • readonly-dropped is an error, and it will fire once per frozen constant typed writable. That is 282 lines on the adopter measured. safe-ts fix readonly-dropped --write repairs them. I kept it an error because the type is false and the fix is mechanical; making it a warning is one line, and it is the owner's call.
  • no-param-mutation reports changes through a copy it did not follow before. Copy the part too, or declare the parameter Mut<...>.
  • A destructured rest is now a copy: rest.count = 1 is no longer reported, rest.meta.tag = ... is.

What stays coarse or unseen

  • Reading against writing. A callee that only reads a shared field it names is reported like one that writes it. The summaries that tell the two apart miss a write through a local or a loop variable, so they cannot show that a callee leaves a field alone.
  • A method of a class that can be extended (exported, extended in its file, abstract) may touch anything: an override may run instead.
  • A copy stored in this and changed later.
  • readonly-dropped does not open package types, mapped or computed types, or unions of object types.

Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review, acceptance tests, the override fix and the merge) in Claude Code.

Based on `ways-out` (#140), and contains it: the diff shown is this piece alone. Two ways to change data that is not yours to change, both passing `tsc` strict, `safe-ts check --idiomatic --deny-warnings` and oxlint. Both came out of an outside audit of `main`; I confirmed each on the binary first. ```ts function rename(order: Order): Order { const copy = { ...order, id: "new" }; // the form `no-param-mutation`'s own advice and oxlint steer you to copy.names.push("x"); // the caller's list copy.meta.tag = "y"; // the caller's object return copy; } type Limits = { retries: number }; export const LIMITS: Limits = Object.freeze({ retries: 3 }); // frozen at run time, writable by its type raise(mut(LIMITS)); // compiles; TypeError when it runs ``` A shallow copy is a new object whose parts are still whoever's they were, and the checker followed only a list made of a single spread. And TypeScript lets `readonly` be dropped by any annotation, so a frozen object can be handed around as writable. ## What changes **`no-param-mutation` follows shallow copies.** An object spread, `Object.assign({}, x)`, a destructured rest, a list with a spread among other elements, `slice()`, `Array.from`, and a copy a helper hands back are new objects whose own slots belong to the function and whose parts stay the parameter's. Changing a part through the copy is reported, and so is lending it with `mut(...)`. Lending a *whole* copy to a `Mut` parameter is reported only where the callee could write something the caller still holds. A field counts as shared when all of these hold: - the copy took it from the parameter and did not give it a value of its own; - something can be written through it, as far down as its type is written (a `readonly T[]` or `ReadonlyMap` of read-only parts is not shared); - the callee's parameter type has it; - the callee names it. A field the callee only gives a new value does not count. The finding names the fields, and its help says to copy them or to write them read-only in the type. That last option turns a convention ("these lists are replaced whole, never changed in place") into something checked. **New rule `readonly-dropped`** (error, with a quick fix). A value whose written type has a `readonly` property, given a place that can write it: an annotated binding, a declared return type, a field, an element of a typed list or map. Types are opened across files. Passing to a parameter that is not `Mut` is a read and stays silent. ## Evidence - **Held-out cases, written by the reviewer and not shown to the implementer.** - Changing a part through a copy: 28 forms, all reported. 17 fine forms, all silent (a part copied too, a field given its own value, `structuredClone`, a `Mut` parameter, the function's own data). - Lending a whole copy: 18 harmful lends reported, 13 harmless ones silent. Three harmless ones are reported by design ("What stays coarse", below). - `readonly-dropped`: 14 of 14 forms reported, 7 fine forms silent. - **Three rounds, and one fix of mine.** The first version judged a whole-copy lend by the copy alone and read only types written in the same file (7 of my 14 forms). The second cost 2.7% of a check. The third added a summary for methods that read the receiver's declared class and so missed an override that changes the shared part; I fixed that by reading only a method no override can replace, as the newest rules already do. - **What the new rule buys.** With one frozen module constant typed writable, `main` catches 3 of 9 ways to write it. After the quick fix (`Readonly<T>` on the annotation), `tsc` refuses the direct writes and the lend, and this rule reports the next step: the constant handed out by a function, kept in a field, pushed into a list. - **On an adopter's project (about 760 files):** - `no-param-mutation`: 5 new findings, each a copy lent whole. Four are a hand-written clone of a large object that shares twelve lists, some on purpose, passed to a function that may change anything. One is a copy whose callee only reads the shared part (coarse, below). - `readonly-dropped`: 282, all of one kind: a frozen object literal declared under a writable type. None is a defect today. On a copy of one of its packages the fix command removed 272 of 273 in one run and surfaced four more of the same kind one step on (the implementer's measurement). - **Soundness corpus:** two classes added and closed (`shallow-copy-shares-object`, `spread-list-shares-elements`). 16 of 105 escape. - **Cost:** +0.97% instructions for a whole check of that project's largest entry, on top of #140 (17.31 to 17.48 billion, one thread, warm cache, callgrind; two runs of each binary agree to 0.01%). The second round cost 2.7%, nearly all of it `readonly-dropped` opening types across files; it now decides most sites in the file and remembers each pair of types for the pass. The work guard's allocation and memo-question counts each rose about 1%. ## What turns red on upgrade - **`readonly-dropped` is an error, and it will fire once per frozen constant typed writable.** That is 282 lines on the adopter measured. `safe-ts fix readonly-dropped --write` repairs them. I kept it an error because the type is false and the fix is mechanical; making it a warning is one line, and it is the owner's call. - `no-param-mutation` reports changes through a copy it did not follow before. Copy the part too, or declare the parameter `Mut<...>`. - A destructured rest is now a copy: `rest.count = 1` is no longer reported, `rest.meta.tag = ...` is. ## What stays coarse or unseen - **Reading against writing.** A callee that only reads a shared field it names is reported like one that writes it. The summaries that tell the two apart miss a write through a local or a loop variable, so they cannot show that a callee leaves a field alone. - **A method of a class that can be extended** (exported, extended in its file, abstract) may touch anything: an override may run instead. - A copy stored in `this` and changed later. - `readonly-dropped` does not open package types, mapped or computed types, or unions of object types. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review, acceptance tests, the override fix and the merge) in Claude Code.
Borrowed data through a copy or a looser type: shallow copies share their parts, readonly dropped by an annotation
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m15s
Tests / test (pull_request) Successful in 10m31s
836835ff61
Two ways to change data that is not the function's to change passed every gate.

A shallow copy of a borrowed parameter (`{ ...order }`, `Object.assign({}, order)`, a rest, a
list with a spread among other elements, a copy a helper hands back) is a new object whose
parts are still the caller's. `no-param-mutation` followed only a list made of one spread. It
now follows the others: a change of a part through the copy is reported, and so is lending the
part. A whole copy lent to a `Mut` parameter is reported where the callee could write
something the copy still shares: a field the copy took, that something can be written through
as far as its type is written, that the callee's parameter type has, and that the callee
names (a function, a static method, or a method no override can replace).

TypeScript lets `readonly` be dropped by any annotation, so a frozen object can be handed
around as writable and a write to it throws when it runs. New rule `readonly-dropped` (error,
with a quick fix): a value whose written type has a `readonly` property given a place that
can write it, with types opened across files.

Soundness corpus: `shallow-copy-shares-object` and `spread-list-shares-elements` added and
closed. Contains the ways-out piece it was merged with: the rewrite list and the work
ceilings are those of the merged tree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee changed target branch from ways-out to main 2026-11-23 13:32:21 +01:00
Merge main: the piece below has landed
Some checks failed
Benchmarks / bench (pull_request) Has been cancelled
Tests / test (pull_request) Has been cancelled
de2d94c1a5
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch shared-copies 2026-11-23 13:32:36 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!141
No description provided.